file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/97/0x346fa0A6f1B77F294Ea799BEdE9473280b3eFFAe/sources/contracts/IERC1155.sol
ERC1155标准的接口合约,实现了EIP1155的功能/
interface IERC1155 is IERC165 { event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll(address indexed account, address indexed operator, bool approved); event URI(string value, uint256 indexed id); function balanceOf(address account, uint256 id) external view returns (uint256); function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address account, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; pragma solidity ^0.8.0; }
5,045,515
./partial_match/4/0xB5cf359Ac5Df39D338dA634a9D5a5E8dBf3268AB/sources/ReferenceToken.sol
-- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- / Generates `_amount` tokens to be assigned to `_tokenHolder` Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. _tokenHolder The address that will be assigned the new tokens _amount The quantity of tokens generated _operatorData Data that will be passed to the recipient as a first transfer
function mint( address _tokenHolder, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external onlyOwner { doMint(_tokenHolder, _amount, _data, _operatorData); }
8,753,508
/** *Submitted for verification at Etherscan.io on 2020-07-08 */ // File: contracts/IERC165.sol pragma solidity ^0.5.11; /** * @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: contracts/IERC721.sol pragma solidity ^0.5.11; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed tokenOwner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed tokenOwner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address tokenOwner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address tokenOwner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address tokenOwner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: contracts/IERC721Receiver.sol pragma solidity ^0.5.11; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: contracts/SafeMath.sol pragma solidity ^0.5.11; /** * @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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/Address.sol pragma solidity ^0.5.11; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } } // File: contracts/Counters.sol pragma solidity ^0.5.11; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: contracts/ERC165.sol pragma solidity ^0.5.11; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: contracts/ERC721.sol pragma solidity ^0.5.11; pragma experimental ABIEncoderV2; /** * @title ERC721 Customized for Microsponsors from: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721MetadataMintable.sol */ /** * @title Deployed Microsponsors Registry smart contract interface. * @dev We just use the signatures of the parts we need to interact with: */ contract DeployedRegistry { function isContentIdRegisteredToCaller(uint32 federationId, string memory contentId) public view returns(bool); function isMinter(uint32 federationId, address account) public view returns (bool); function isAuthorizedTransferFrom(uint32 federationId, address from, address to, uint256 tokenId, address minter, address owner) public view returns(bool); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; /*** Contract data ***/ /// @dev owner1, owner2 Admins of this contract. address public owner1; address public owner2; /// @dev paused Admin only. Set to `true` to stop token minting and transfers. bool public paused = false; /// @dev mintFee Admin only. Set minting fee; default fee is below (in wei). uint256 public mintFee = 100000000000000; /// @dev DeployedRegistry The Microsponsors Registry Contract that verifies participants. /// Admin can update the contract address here to upgrade Registry. DeployedRegistry public registry; /// @title _tokenIds All Token IDs minted, incremented starting at 1 Counters.Counter _tokenIds; /// @dev _tokenOwner mapping from Token ID to Token Owner mapping (uint256 => address) private _tokenOwner; /// @dev _ownedTokensCount mapping from Token Owner to # of owned tokens mapping (address => Counters.Counter) private _ownedTokensCount; /// @dev _mintedTokensCount mapping from Token Minter to # of minted tokens mapping (address => Counters.Counter) private _mintedTokensCount; /// @dev tokenToFederationId see notes on path to federation in Microsponsors Registry contract mapping (uint256 => uint32) public tokenToFederationId; /// @dev TimeSlot metadata struct for each token /// TimeSlots timestamps are stored as uint48: /// https://medium.com/@novablitz/storing-structs-is-costing-you-gas-774da988895e struct TimeSlot { address minter; // the address of the user who mint()'ed this time slot string contentId; // the users' registered contentId containing the Property string propertyName; // describes the Property within the contentId that is tokenized into time slots uint48 startTime; // min timestamp (when time slot begins) uint48 endTime; // max timestamp (when time slot ends) uint48 auctionEndTime; // max timestamp (when auction for time slot ends) uint16 category; // integer that represents the category (see Microsponsors utils.js) bool isSecondaryTradingEnabled; // if true, first buyer can trade to others } /// @dev _tokenToTimeSlot mapping from Token ID to TimeSlot struct /// Use tokenTimeSlot() public method to read mapping(uint256 => TimeSlot) private _tokenToTimeSlot; /// @dev PropertyNameStruct: name of the time slot struct PropertyNameStruct { string propertyName; } /// @dev _tokenMinterToPropertyName mapping from Minter => Content ID => array of Property Names /// Used to display all tokenized Time Slots on a given Property. /// Using struct because there is no mapping to a dynamic array of bytes32 in Solidity at this time. mapping(address => mapping(string => PropertyNameStruct[])) private _tokenMinterToPropertyNames; /// @dev ContentIdStruct The registered Content ID, verified by Registry contract struct ContentIdStruct { string contentId; } /// @dev _tokenMinterToContentIds Mapping from Token Minter to array of Content IDs /// that they have *ever* minted tokens for mapping(address => ContentIdStruct[]) private _tokenMinterToContentIds; /// @dev _tokenURIs Mapping from Token ID to Token URIs mapping(uint256 => string) private _tokenURIs; /// @dev _tokenApprovals Mapping from Token ID to Approved Address mapping (uint256 => address) private _tokenApprovals; /// @dev _operatorApprovals Mapping from Token Owner to Operator Approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; // @dev 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; constructor () public { // Register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); // Set the contract owners to msg.sender by default owner1 = _msgSender(); owner2 = _msgSender(); } /** * @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 not 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). */ function _msgSender() internal view returns (address) { 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; } /*** Owner (Administrator) functions ***/ /** * @dev Sets the contract's owner (administrator) * Based on 0x's Ownable, but modified here */ modifier onlyOwner() { require( (_msgSender() == owner1) || (_msgSender() == owner2), "ONLY_CONTRACT_OWNER" ); _; } /** * @dev Transfer owner (admin) functions to another address * @param newOwner Address of new owner/ admin of contract */ function transferOwnership1(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner1 = newOwner; } } function transferOwnership2(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner2 = newOwner; } } /** * @dev Update contract address for Microsponsors Registry contract * @param newAddress where the Registry contract lives */ function updateRegistryAddress(address newAddress) public onlyOwner { registry = DeployedRegistry(newAddress); } /** * @dev Update the fee (in wei) charged for minting a single token */ function updateMintFee(uint256 val) public onlyOwner { mintFee = val; } /// @dev Pausable (adapted from OpenZeppelin via Cryptokitties) /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by contract owner to pause minting and transfers. function pause() public onlyOwner whenNotPaused { paused = true; } /// @dev Called by contract owner to unpause minting and transfers. function unpause() public onlyOwner whenPaused { paused = false; } /// @dev Admin withdraws entire balance from contract. function withdrawBalance() public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL // Ref: https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/ uint balance = address(this).balance; (bool success, ) = msg.sender.call.value(balance)(""); require(success, "WITHDRAW_FAILED"); } /*** Minting tokens ***/ /** * @dev Function to mint tokens. * @return tokenId */ function mint( string memory contentId, string memory propertyName, uint48 startTime, uint48 endTime, uint48 auctionEndTime, uint16 category, bool isSecondaryTradingEnabled, uint32 federationId ) public payable whenNotPaused returns (uint256) { require(msg.value >= mintFee); require(federationId > 0, "INVALID_FEDERATION_ID"); require( registry.isMinter(federationId, _msgSender()), "CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE" ); require( _isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId), "INVALID_TIME_SLOT" ); uint256 tokenId = _mint(_msgSender()); _setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled); tokenToFederationId[tokenId] = federationId; return tokenId; } /** * @dev Function to mint tokens. * @param tokenURI The token URI of the minted token. * @return tokenId */ function mintWithTokenURI( string memory contentId, string memory propertyName, uint48 startTime, uint48 endTime, uint48 auctionEndTime, uint16 category, bool isSecondaryTradingEnabled, uint32 federationId, string memory tokenURI ) public payable whenNotPaused returns (uint256) { require(msg.value >= mintFee); require(federationId > 0, "INVALID_FEDERATION_ID"); require( registry.isMinter(federationId, _msgSender()), "CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE" ); require( _isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId), "INVALID_TIME_SLOT" ); uint256 tokenId = _mint(_msgSender()); _setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled); _setTokenURI(tokenId, tokenURI); tokenToFederationId[tokenId] = federationId; return tokenId; } /** * @dev Function to safely mint tokens. * @return tokenId */ function safeMint( string memory contentId, string memory propertyName, uint48 startTime, uint48 endTime, uint48 auctionEndTime, uint16 category, bool isSecondaryTradingEnabled, uint32 federationId ) public payable whenNotPaused returns (uint256) { require(msg.value >= mintFee); require(federationId > 0, "INVALID_FEDERATION_ID"); require( registry.isMinter(federationId, _msgSender()), "CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE" ); require( _isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId), "INVALID_TIME_SLOT" ); uint256 tokenId = _safeMint(_msgSender()); _setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled); tokenToFederationId[tokenId] = federationId; return tokenId; } /** * @dev Function to safely mint tokens. * @param data bytes data to send along with a safe transfer check. * @return tokenId */ function safeMint( string memory contentId, string memory propertyName, uint48 startTime, uint48 endTime, uint48 auctionEndTime, uint16 category, bool isSecondaryTradingEnabled, uint32 federationId, bytes memory data ) public payable whenNotPaused returns (uint256) { require(msg.value >= mintFee); require(federationId > 0, "INVALID_FEDERATION_ID"); require( registry.isMinter(federationId, _msgSender()), "CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE" ); require( _isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId), "INVALID_TIME_SLOT" ); uint256 tokenId = _safeMint(_msgSender(), data); _setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled); tokenToFederationId[tokenId] = federationId; return tokenId; } /** * @param tokenURI The token URI of the minted token. * @return tokenId */ function safeMintWithTokenURI( string memory contentId, string memory propertyName, uint48 startTime, uint48 endTime, uint48 auctionEndTime, uint16 category, bool isSecondaryTradingEnabled, uint32 federationId, string memory tokenURI ) public payable whenNotPaused returns (uint256) { require(msg.value >= mintFee); require(federationId > 0, "INVALID_FEDERATION_ID"); require( registry.isMinter(federationId, _msgSender()), "CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE" ); require( _isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId), "INVALID_TIME_SLOT" ); uint256 tokenId = _safeMint(_msgSender()); _setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled); _setTokenURI(tokenId, tokenURI); tokenToFederationId[tokenId] = federationId; return tokenId; } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @return tokenId */ function _safeMint(address to) internal returns (uint256) { uint256 tokenId = _safeMint(to, ""); return tokenId; } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param data bytes data to send along with a safe transfer check * @return tokenId */ function _safeMint(address to, bytes memory data) internal returns (uint256) { uint256 tokenId = _mint(to); require( _checkOnERC721Received(address(0), to, tokenId, data), "TRANSFER_TO_NON_ERC721RECEIVER_IMPLEMENTER" ); return tokenId; } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token */ function _mint(address to) internal returns (uint256) { require(to != address(0), "MINT_TO_ZERO_ADDRESS"); _tokenIds.increment(); uint256 tokenId = _tokenIds.current(); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); _mintedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); return tokenId; } /*** Token URIs ***/ /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require( _exists(tokenId), "NON_EXISTENT_TOKEN" ); _tokenURIs[tokenId] = uri; } /** * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query * @return URI for a given token ID. */ function tokenURI(uint256 tokenId) public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL require( _exists(tokenId), "NON_EXISTENT_TOKEN" ); return _tokenURIs[tokenId]; } /*** Token TimeSlot data and metadata ***/ function _isValidTimeSlot( string memory contentId, uint48 startTime, uint48 endTime, uint48 auctionEndTime, uint32 federationId ) internal view returns (bool) { require( registry.isContentIdRegisteredToCaller(federationId, contentId), "CONTENT_ID_NOT_REGISTERED_TO_CALLER" ); require( startTime > auctionEndTime, "START_TIME_AFTER_AUCTION_END_TIME" ); require( endTime > startTime, "START_TIME_AFTER_END_TIME" ); return true; } function _isContentIdMappedToMinter( string memory contentId ) internal view returns (bool) { ContentIdStruct[] memory a = _tokenMinterToContentIds[msg.sender]; bool foundMatch = false; for (uint i = 0; i < a.length; i++) { if (stringsMatch(contentId, a[i].contentId)) { foundMatch = true; } } return foundMatch; } function _isPropertyNameMappedToMinter( string memory contentId, string memory propertyName ) internal view returns (bool) { PropertyNameStruct[] memory a = _tokenMinterToPropertyNames[msg.sender][contentId]; bool foundMatch = false; for (uint i = 0; i < a.length; i++) { if (stringsMatch(propertyName, a[i].propertyName)) { foundMatch = true; } } return foundMatch; } function _setTokenTimeSlot( uint256 tokenId, string memory contentId, string memory propertyName, uint48 startTime, uint48 endTime, uint48 auctionEndTime, uint16 category, bool isSecondaryTradingEnabled ) internal { require( _exists(tokenId), "NON_EXISTENT_TOKEN" ); TimeSlot memory _timeSlot = TimeSlot({ minter: address(_msgSender()), contentId: string(contentId), propertyName: string(propertyName), startTime: uint48(startTime), endTime: uint48(endTime), auctionEndTime: uint48(auctionEndTime), category: uint16(category), isSecondaryTradingEnabled: bool(isSecondaryTradingEnabled) }); _tokenToTimeSlot[tokenId] = _timeSlot; if (!_isContentIdMappedToMinter(contentId)) { _tokenMinterToContentIds[_msgSender()].push( ContentIdStruct(contentId) ); } if (!_isPropertyNameMappedToMinter(contentId, propertyName)) { _tokenMinterToPropertyNames[_msgSender()][contentId].push( PropertyNameStruct(propertyName) ); } } function tokenTimeSlot(uint256 tokenId) public view returns ( address minter, address owner, string memory contentId, string memory propertyName, uint48 startTime, uint48 endTime, uint48 auctionEndTime, uint16 category, bool isSecondaryTradingEnabled, uint32 federationId ) { require( _exists(tokenId), "NON_EXISTENT_TOKEN" ); TimeSlot memory _timeSlot = _tokenToTimeSlot[tokenId]; uint32 _federationId = tokenToFederationId[tokenId]; return ( _timeSlot.minter, ownerOf(tokenId), _timeSlot.contentId, _timeSlot.propertyName, _timeSlot.startTime, _timeSlot.endTime, _timeSlot.auctionEndTime, _timeSlot.category, _timeSlot.isSecondaryTradingEnabled, _federationId ); } /*** Token minter queries ***/ /// @dev Look up all Content IDs a Minter has tokenized TimeSlots for. /// We're not getting this from the Registry because we want to keep /// a separate record here of all Content ID's the acct has *ever* /// minted tokens for. The registry is for keeping track of their /// current (not necessarily past) Content ID registrations. function tokenMinterContentIds(address minter) public view returns (string[] memory) { //inject PUBLIC FUNC TO EXTERNAL ContentIdStruct[] memory m = _tokenMinterToContentIds[minter]; string[] memory r = new string[](m.length); for (uint i = 0; i < m.length; i++) { r[i] = m[i].contentId; } return r; } /// @dev Look up all Property Names a Minter has created Time Slots for /// with a particular Content ID function tokenMinterPropertyNames( address minter, string calldata contentId ) external view returns (string[] memory) { PropertyNameStruct[] memory m = _tokenMinterToPropertyNames[minter][contentId]; string[] memory r = new string[](m.length); for (uint i = 0; i < m.length; i++) { r[i] = m[i].propertyName; } return r; } /** * Return all the Token IDs minted by a given account. * @dev This method MUST NEVER be called by smart contract code. First, it's fairly * expensive (it walks the entire _tokenIds array looking for tokens belonging to minter), * but it also returns a dynamic array, which is only supported for web3 calls, and * not contract-to-contract calls (at this time). */ function tokensMintedBy(address minter) public view returns (uint256[] memory) { //inject PUBLIC FUNC TO EXTERNAL require( minter != address(0), "CANNOT_QUERY_ZERO_ADDRESS" ); uint256 tokenCount = _mintedTokensCount[minter].current(); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = totalSupply(); uint256 resultIndex = 0; // All Tokens have IDs starting at 1 and increase // sequentially up to the total supply count. uint256 tokenId; for (tokenId = 1; tokenId <= totalTokens; tokenId++) { if (_tokenToTimeSlot[tokenId].minter == minter) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } /*** Token balance and ownership queries ***/ /** * @dev Gets the total number of tokens ever minted. */ function totalSupply() public view returns (uint256) { return _tokenIds.current(); } /** * @dev Gets the balance of the specified address. * @param tokenOwner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address tokenOwner) public view returns (uint256) { require( tokenOwner != address(0), "CANNOT_QUERY_ZERO_ADDRESS" ); return _ownedTokensCount[tokenOwner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address tokenOwner = _tokenOwner[tokenId]; return tokenOwner; } /** * @param tokenOwner The owner whose tokens we are interested in. * @dev This method MUST NEVER be called by smart contract code. First, it's fairly * expensive (it walks the entire _tokenIds array looking for tokens belonging to owner), * but it also returns a dynamic array, which is only supported for web3 calls, and * not contract-to-contract calls (at this time). */ function tokensOfOwner(address tokenOwner) public view returns(uint256[] memory) { //inject PUBLIC FUNC TO EXTERNAL uint256 tokenCount = balanceOf(tokenOwner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = totalSupply(); uint256 resultIndex = 0; // All Tokens have IDs starting at 1 and increase // sequentially up to the total count. uint256 tokenId; for (tokenId = 1; tokenId <= totalTokens; tokenId++) { if (_tokenOwner[tokenId] == tokenOwner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } /*** Approvals & Transfers ***/ /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public whenNotPaused { address tokenOwner = ownerOf(tokenId); require( to != tokenOwner, "APPROVAL_IS_REDUNDANT" ); require( _msgSender() == tokenOwner || isApprovedForAll(tokenOwner, _msgSender()), "CALLER_NOT_AUTHORIZED" ); _tokenApprovals[tokenId] = to; emit Approval(tokenOwner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require( _exists(tokenId), "NON_EXISTENT_TOKEN" ); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public whenNotPaused { require(to != _msgSender(), "CALLER_CANNOT_APPROVE_SELF"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given token owner. * @param tokenOwner token owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the token owner */ function isApprovedForAll(address tokenOwner, address operator) public view returns (bool) { return _operatorApprovals[tokenOwner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public whenNotPaused { require( _isApprovedOrOwner(_msgSender(), tokenId), "UNAUTHORIZED_TRANSFER" ); address minter = _tokenToTimeSlot[tokenId].minter; address owner = ownerOf(tokenId); uint32 federationId = tokenToFederationId[tokenId]; if (_tokenToTimeSlot[tokenId].isSecondaryTradingEnabled == false) { require( isSecondaryTrade(from, to, tokenId) == false, "SECONDARY_TRADING_DISABLED" ); } require( registry.isAuthorizedTransferFrom(federationId, from, to, tokenId, minter, owner), "UNAUTHORIZED_TRANSFER" ); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public whenNotPaused { require( _isApprovedOrOwner(_msgSender(), tokenId), "UNAUTHORIZED_TRANSFER" ); address minter = _tokenToTimeSlot[tokenId].minter; address owner = ownerOf(tokenId); uint32 federationId = tokenToFederationId[tokenId]; if (_tokenToTimeSlot[tokenId].isSecondaryTradingEnabled == false) { require( isSecondaryTrade(from, to, tokenId) == false, "SECONDARY_TRADING_DISABLED" ); } require( registry.isAuthorizedTransferFrom(federationId, from, to, tokenId, minter, owner), "UNAUTHORIZED_TRANSFER" ); _safeTransferFrom(from, to, tokenId, data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) internal { _transferFrom(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, data), "TRANSFER_TO_NON_ERC721RECEIVER_IMPLEMENTER" ); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address tokenOwner = _tokenOwner[tokenId]; return tokenOwner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( _exists(tokenId), "NON_EXISTENT_TOKEN" ); address tokenOwner = ownerOf(tokenId); return (spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, spender)); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require( ownerOf(tokenId) == from, "UNAUTHORIZED_TRANSFER" ); require( to != address(0), "TRANSFER_TO_ZERO_ADDRESS" ); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } /*** Burn Tokens ***/ // solhint-disable /** * @dev Customized for Microsponsors * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721Burnable.sol * @dev Burns a specific ERC721 token. * @param tokenId uint256 id of the ERC721 token to be burned */ // solhint-enable function burn(uint256 tokenId) public whenNotPaused { address minter = _tokenToTimeSlot[tokenId].minter; address tokenOwner = ownerOf(tokenId); uint32 federationId = tokenToFederationId[tokenId]; if (tokenOwner == minter) { require( registry.isMinter(federationId, _msgSender()), "UNAUTHORIZED_BURN" ); } require( _isApprovedOrOwner(_msgSender(), tokenId), "UNAUTHORIZED_BURN" ); _burn(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param tokenOwner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address tokenOwner, uint256 tokenId) internal { require( ownerOf(tokenId) == tokenOwner, "UNAUTHORIZED_BURN" ); _clearApproval(tokenId); _ownedTokensCount[tokenOwner].decrement(); _tokenOwner[tokenId] = address(0); // Clear token URIs (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } // Clear time slot data delete _tokenToTimeSlot[tokenId]; emit Transfer(tokenOwner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /*** Helper fns ***/ function stringsMatch ( string memory a, string memory b ) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) ); } function isSecondaryTrade ( address from, address to, uint256 tokenId ) internal view returns (bool) { address minter = _tokenToTimeSlot[tokenId].minter; if (from == minter || to == minter) { return false; } else { return true; } } } // File: contracts/Microsponsors.sol /** * Customized for Microsponsors * from Open Zeppelin's ERC721Metadata contract, which is MIT Licensed: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721Metadata.sol 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. */ contract Microsponsors is ERC721 { // Token name string private _name; // Token symbol string private _symbol; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol, address registryAddress) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); super.updateRegistryAddress(registryAddress); } /** * @dev Gets the token name. * @return string representing the token name */ function name() public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL return _symbol; } }
inject PUBLIC FUNC TO EXTERNAL
function tokenURI(uint256 tokenId) public view returns (string memory) {
922,019
pragma solidity ^0.5.10; import {SafeMath} from "@summa-tx/bitcoin-spv-sol/contracts/SafeMath.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {CheckBitcoinSigs} from "@summa-tx/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "./TBTCConstants.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; library DepositRedemption { using SafeMath for uint256; using CheckBitcoinSigs for bytes; using BytesLib for bytes; using BTCUtils for bytes; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Pushes signer fee to the Keep group by transferring it to the Keep address /// @dev Approves the keep contract, then expects it to call transferFrom function distributeSignerFee(DepositUtils.Deposit storage _d) internal { address _tbtcTokenAddress = _d.TBTCToken; TBTCToken _tbtcToken = TBTCToken(_tbtcTokenAddress); IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _tbtcToken.approve(_d.keepAddress, _d.signerFee()); _keep.distributeERC20ToMembers(_tbtcTokenAddress, _d.signerFee()); } /// @notice Approves digest for signing by a keep /// @dev Calls given keep to sign the digest. Records a current timestamp /// for given digest /// @param _digest Digest to approve function approveDigest(DepositUtils.Deposit storage _d, bytes32 _digest) internal { IBondedECDSAKeep(_d.keepAddress).sign(_digest); _d.approvedDigests[_digest] = block.timestamp; } /// @notice Handles TBTC requirements for redemption /// @dev Burns or transfers depending on term and supply-peg impact function performRedemptionTBTCTransfers(DepositUtils.Deposit storage _d) internal { TBTCToken _tbtc = TBTCToken(_d.TBTCToken); address tdtHolder = _d.depositOwner(); address vendingMachine = _d.VendingMachine; uint256 tbtcLot = _d.lotSizeTbtc(); uint256 signerFee = _d.signerFee(); uint256 tbtcOwed = _d.getRedemptionTbtcRequirement(_d.redeemerAddress); // if we owe 0 TBTC, msg.sender is TDT owner and FRT holder. if(tbtcOwed == 0){ return; } // if we owe > 0 & < signerfee, msg.sender is TDT owner but not FRT holder. if(tbtcOwed <= signerFee){ _tbtc.transferFrom(msg.sender, address(this), tbtcOwed); return; } // Redemmer always owes a full TBTC for at-term redemption. if(tbtcOwed == tbtcLot){ // the TDT holder has exclusive redemption rights to a UXTO up until the deposit’s term. // At that point, we open it up so anyone may redeem it. // As compensation, the TDT owner is reimbursed in TBTC // Vending Machine-owned TDTs have been used to mint TBTC, // and we should always burn a full TBTC to redeem the deposit. if(tdtHolder == vendingMachine){ _tbtc.burnFrom(msg.sender, tbtcLot); } // if signer fee is not escrowed, escrow and it here and send the rest to TDT owner else if(_tbtc.balanceOf(address(this)) < signerFee){ _tbtc.transferFrom(msg.sender, address(this), signerFee); _tbtc.transferFrom(msg.sender, tdtHolder, tbtcLot.sub(signerFee)); } // tansfer a full TBTC to TDT owner if signerFee is escrowed else{ _tbtc.transferFrom(msg.sender, tdtHolder, tbtcLot); } return; } revert("tbtcOwed value must be 0, SignerFee, or a full TBTC"); } function _requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _redeemer ) internal { require(_d.inRedeemableState(), "Redemption only available from Active or Courtesy state"); require(_redeemerOutputScript.length > 0, "cannot send value to zero output script"); // set redeemerAddress early to enable direct access by other functions _d.redeemerAddress = _redeemer; performRedemptionTBTCTransfers(_d); // Convert the 8-byte LE ints to uint256 uint256 _outputValue = abi.encodePacked(_outputValueBytes).reverseEndianness().bytesToUint(); uint256 _requestedFee = _d.utxoSize().sub(_outputValue); require(_requestedFee >= TBTCConstants.getMinimumRedemptionFee(), "Fee is too low"); // Calculate the sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoSizeBytes, _outputValueBytes, _redeemerOutputScript); // write all request details _d.redeemerOutputScript = _redeemerOutputScript; _d.initialRedemptionFee = _requestedFee; _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( _redeemer, _sighash, _d.utxoSize(), _redeemerOutputScript, _requestedFee, _d.utxoOutpoint); } /// @notice Anyone can request redemption as long as they can /// approve the TDT transfer to the final recipient. /// @dev The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption /// on behalf of _finalRecipient. /// @param _d deposit storage pointer /// @param _outputValueBytes The 8-byte LE output size /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { IERC721 _tbtcDepositToken = IERC721(_d.TBTCDepositToken); _tbtcDepositToken.transferFrom(msg.sender, _finalRecipient, uint256(address(this))); _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, _finalRecipient); } /// @notice Only TDT owner can request redemption, /// unless Deposit is expired or in COURTESY_CALL. /// @dev The redeemer specifies details about the Bitcoin redemption tx /// @param _d deposit storage pointer /// @param _outputValueBytes The 8-byte LE output size /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, msg.sender); } /// @notice Anyone may provide a withdrawal signature if it was requested /// @dev The signers will be penalized if this (or provideRedemptionProof) is not called /// @param _d deposit storage pointer /// @param _v Signature recovery value /// @param _r Signature R value /// @param _s Signature S value function provideRedemptionSignature( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s ) public { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); // If we're outside of the signature window, we COULD punish signers here // Instead, we consider this a no-harm-no-foul situation. // The signers have not stolen funds. Most likely they've just inconvenienced someone // The signature must be valid on the pubkey require( _d.signerPubkey().checkSig( _d.lastRequestedDigest, _v, _r, _s ), "Invalid signature" ); // A signature has been provided, now we wait for fee bump or redemption _d.setAwaitingWithdrawalProof(); _d.logGotRedemptionSignature( _d.lastRequestedDigest, _r, _s); } /// @notice Anyone may notify the contract that a fee bump is needed /// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE /// @param _d deposit storage pointer /// @param _previousOutputValueBytes The previous output's value /// @param _newOutputValueBytes The new output's value /// @return True if successful, False if prevented by timeout, otherwise revert function increaseRedemptionFee( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public returns (bool) { require(_d.inAwaitingWithdrawalProof(), "Fee increase only available after signature provided"); require(block.timestamp >= _d.withdrawalRequestTime + TBTCConstants.getIncreaseFeeTimer(), "Fee increase not yet permitted"); uint256 _newOutputValue = checkRelationshipToPrevious(_d, _previousOutputValueBytes, _newOutputValueBytes); // Calculate the next sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoSizeBytes, _newOutputValueBytes, _d.redeemerOutputScript); // Ratchet the signature and redemption proof timeouts _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); // Go back to waiting for a signature _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( msg.sender, _sighash, _d.utxoSize(), _d.redeemerOutputScript, _d.utxoSize().sub(_newOutputValue), _d.utxoOutpoint); } function checkRelationshipToPrevious( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public view returns (uint256 _newOutputValue){ // Check that we're incrementing the fee by exactly the redeemer's initial fee uint256 _previousOutputValue = DepositUtils.bytes8LEToUint(_previousOutputValueBytes); _newOutputValue = DepositUtils.bytes8LEToUint(_newOutputValueBytes); require(_previousOutputValue.sub(_newOutputValue) == _d.initialRedemptionFee, "Not an allowed fee step"); // Calculate the previous one so we can check that it really is the previous one bytes32 _previousSighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoSizeBytes, _previousOutputValueBytes, _d.redeemerOutputScript); require( _d.wasDigestApprovedForSigning(_previousSighash) == _d.withdrawalRequestTime, "Provided previous value does not yield previous sighash" ); } /// @notice Anyone may provide a withdrawal proof to prove redemption /// @dev The signers will be penalized if this is not called /// @param _d deposit storage pointer /// @param _txVersion Transaction version number (4-byte LE) /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs /// @param _txLocktime Final 4 bytes of the transaction /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed) /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers function provideRedemptionProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { bytes32 _txid; uint256 _fundingOutputValue; require(_d.inRedemption(), "Redemption proof only allowed from redemption flow"); _fundingOutputValue = redemptionTransactionChecks(_d, _txInputVector, _txOutputVector); _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _d.checkProofFromTxId(_txid, _merkleProof, _txIndexInBlock, _bitcoinHeaders); require((_d.utxoSize().sub(_fundingOutputValue)) <= _d.initialRedemptionFee * 5, "Fee unexpectedly very high"); // Transfer TBTC to signers distributeSignerFee(_d); _d.distributeFeeRebate(); // We're done yey! _d.setRedeemed(); _d.redemptionTeardown(); _d.logRedeemed(_txid); } /// @notice Check the redemption transaction input and output vector to ensure the transaction spends /// the correct UTXO and sends value to the appropreate public key hash /// @dev We only look at the first input and first output. Revert if we find the wrong UTXO or value recipient. /// It's safe to look at only the first input/output as anything that breaks this can be considered fraud /// and can be caught by ECDSAFraudProof /// @param _d deposit storage pointer /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs /// @return The value sent to the redeemer's public key hash function redemptionTransactionChecks( DepositUtils.Deposit storage _d, bytes memory _txInputVector, bytes memory _txOutputVector ) public view returns (uint256) { require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes memory _input = _txInputVector.slice(1, _txInputVector.length-1); bytes memory _output = _txOutputVector.slice(1, _txOutputVector.length-1); require( keccak256(_input.extractOutpoint()) == keccak256(_d.utxoOutpoint), "Tx spends the wrong UTXO" ); require( keccak256(_output.slice(8, 3).concat(_output.extractHash())) == keccak256(abi.encodePacked(_d.redeemerOutputScript)), "Tx sends value to wrong pubkeyhash" ); return (uint256(_output.extractValue())); } /// @notice Anyone may notify the contract that the signers have failed to produce a signature /// @dev This is considered fraud, and is punished /// @param _d deposit storage pointer function notifySignatureTimeout(DepositUtils.Deposit storage _d) public { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); require(block.timestamp > _d.withdrawalRequestTime + TBTCConstants.getSignatureTimeout(), "Signature timer has not elapsed"); _d.startSignerAbortLiquidation(); // not fraud, just failure } /// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof /// @dev This is considered fraud, and is punished /// @param _d deposit storage pointer function notifyRedemptionProofTimeout(DepositUtils.Deposit storage _d) public { require(_d.inAwaitingWithdrawalProof(), "Not currently awaiting a redemption proof"); require(block.timestamp > _d.withdrawalRequestTime + TBTCConstants.getRedemptionProofTimeout(), "Proof timer has not elapsed"); _d.startSignerAbortLiquidation(); // not fraud, just failure } }
Anyone can request redemption as long as they can approve the TDT transfer to the final recipient. The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption on behalf of _finalRecipient. _d deposit storage pointer _outputValueBytes The 8-byte LE output size _redeemerOutputScript The redeemer's length-prefixed output script. _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer.
function transferAndRequestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { IERC721 _tbtcDepositToken = IERC721(_d.TBTCDepositToken); _tbtcDepositToken.transferFrom(msg.sender, _finalRecipient, uint256(address(this))); _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, _finalRecipient); }
1,013,611
pragma solidity 0.4.25; // File: contracts/sogur/interfaces/IModelDataSource.sol /** * @title Model Data Source Interface. */ interface IModelDataSource { /** * @dev Get interval parameters. * @param _rowNum Interval row index. * @param _colNum Interval column index. * @return Interval minimum amount of SGR. * @return Interval maximum amount of SGR. * @return Interval minimum amount of SDR. * @return Interval maximum amount of SDR. * @return Interval alpha value (scaled up). * @return Interval beta value (scaled up). */ function getInterval(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256, uint256, uint256, uint256, uint256); /** * @dev Get interval alpha and beta. * @param _rowNum Interval row index. * @param _colNum Interval column index. * @return Interval alpha value (scaled up). * @return Interval beta value (scaled up). */ function getIntervalCoefs(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256); /** * @dev Get the amount of SGR required for moving to the next minting-point. * @param _rowNum Interval row index. * @return Required amount of SGR. */ function getRequiredMintAmount(uint256 _rowNum) external view returns (uint256); } // File: openzeppelin-solidity-v1.12.0/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity-v1.12.0/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/sogur/ModelDataSource.sol /** * Details of usage of licenced software see here: https://www.sugor.org/software/readme_v1 */ /** * @title Model Data Source. */ contract ModelDataSource is IModelDataSource, Claimable { string public constant VERSION = "1.0.0"; struct Interval { uint256 minN; uint256 maxN; uint256 minR; uint256 maxR; uint256 alpha; uint256 beta; } bool public intervalListsLocked; Interval[11][95] public intervalLists; /** * @dev Lock the interval lists. */ function lock() external onlyOwner { intervalListsLocked = true; } /** * @dev Set interval parameters. * @param _rowNum Interval row index. * @param _colNum Interval column index. * @param _minN Interval minimum amount of SGR. * @param _maxN Interval maximum amount of SGR. * @param _minR Interval minimum amount of SDR. * @param _maxR Interval maximum amount of SDR. * @param _alpha Interval alpha value (scaled up). * @param _beta Interval beta value (scaled up). */ function setInterval(uint256 _rowNum, uint256 _colNum, uint256 _minN, uint256 _maxN, uint256 _minR, uint256 _maxR, uint256 _alpha, uint256 _beta) external onlyOwner { require(!intervalListsLocked, "interval lists are already locked"); intervalLists[_rowNum][_colNum] = Interval({minN: _minN, maxN: _maxN, minR: _minR, maxR: _maxR, alpha: _alpha, beta: _beta}); } /** * @dev Get interval parameters. * @param _rowNum Interval row index. * @param _colNum Interval column index. * @return Interval minimum amount of SGR. * @return Interval maximum amount of SGR. * @return Interval minimum amount of SDR. * @return Interval maximum amount of SDR. * @return Interval alpha value (scaled up). * @return Interval beta value (scaled up). */ function getInterval(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256, uint256, uint256, uint256, uint256) { Interval storage interval = intervalLists[_rowNum][_colNum]; return (interval.minN, interval.maxN, interval.minR, interval.maxR, interval.alpha, interval.beta); } /** * @dev Get interval alpha and beta. * @param _rowNum Interval row index. * @param _colNum Interval column index. * @return Interval alpha value (scaled up). * @return Interval beta value (scaled up). */ function getIntervalCoefs(uint256 _rowNum, uint256 _colNum) external view returns (uint256, uint256) { Interval storage interval = intervalLists[_rowNum][_colNum]; return (interval.alpha, interval.beta); } /** * @dev Get the amount of SGR required for moving to the next minting-point. * @param _rowNum Interval row index. * @return Required amount of SGR. */ function getRequiredMintAmount(uint256 _rowNum) external view returns (uint256) { uint256 currMaxN = intervalLists[_rowNum + 0][0].maxN; uint256 nextMinN = intervalLists[_rowNum + 1][0].minN; assert(nextMinN >= currMaxN); return nextMinN - currMaxN; } } // File: contracts/sogur/BatchSetModelDataSource.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title Batch Set Model Data Source. */ contract BatchSetModelDataSource is Claimable { string public constant VERSION = "1.0.0"; uint256 public constant MAX_INTERVAL_INPUT_LENGTH = 32; ModelDataSource public modelDataSource; /* * @dev Create the contract. */ constructor(address _modelDataSourceAddress) public { require(_modelDataSourceAddress != address(0), "model data source address is illegal"); modelDataSource = ModelDataSource(_modelDataSourceAddress); } /** * @dev Set model data source intervals. */ function setIntervals(uint256 _intervalsCount, uint256[MAX_INTERVAL_INPUT_LENGTH] _rowNum, uint256[MAX_INTERVAL_INPUT_LENGTH] _colNum, uint256[MAX_INTERVAL_INPUT_LENGTH] _minN, uint256[MAX_INTERVAL_INPUT_LENGTH] _maxN, uint256[MAX_INTERVAL_INPUT_LENGTH] _minR, uint256[MAX_INTERVAL_INPUT_LENGTH] _maxR, uint256[MAX_INTERVAL_INPUT_LENGTH] _alpha, uint256[MAX_INTERVAL_INPUT_LENGTH] _beta) external onlyOwner { require(_intervalsCount < MAX_INTERVAL_INPUT_LENGTH, "intervals count must be lower than MAX_INTERVAL_INPUT_LENGTH"); for (uint256 i = 0; i < _intervalsCount; i++) { modelDataSource.setInterval(_rowNum[i], _colNum[i], _minN[i], _maxN[i], _minR[i], _maxR[i], _alpha[i], _beta[i]); } } /** * @dev Claim model data source ownership. */ function claimOwnershipModelDataSource() external onlyOwner { modelDataSource.claimOwnership(); } /** * @dev Renounce model data source ownership. */ function renounceOwnershipModelDataSource() external onlyOwner { modelDataSource.renounceOwnership(); } /** * @dev Lock model data source. */ function lockModelDataSource() external onlyOwner { modelDataSource.lock(); } }
Lock the interval lists./
function lock() external onlyOwner { intervalListsLocked = true; }
6,309,243
./full_match/1/0x6091767Be457a5A7f7d368dD68Ebf2f416728d97/sources/contracts/feeDistributor/ElOnlyFeeDistributor.sol
@inheritdoc IFeeDistributor client address
function eth2WithdrawalCredentialsAddress() external override view returns (address) { return s_clientConfig.recipient; }
3,112,944
./partial_match/1/0x2459197966cf90f4092378A89f06921400a4c3b2/sources/TitanFeeMaker.sol
require(wethBalance > 0,'TitanSwapV1FeeMaker: weth amount == 0'); TransferHelper.safeTransfer(weth,to,wethBalance);
function withdrawETH(address to) external override onlyOwner{ uint256 wethBalance = IERC20(weth).balanceOf(address(this)); IWETH(weth).withdraw(wethBalance); TransferHelper.safeTransferETH(to,wethBalance); }
3,885,811
./full_match/1/0xe6BBD98394d252f97D644A4F204F47754A7Ba1bF/sources/contracts/ConvexExecutor/Frax/ConvexPositionHandler.sol
/ estimate amount of USDC received based on stable peg i.e., 1FXS = 1 3Pool LP Token burn Lp tokens to receive USDC with a slippage of `maxSlippage`
function _convertLpTokenIntoUSDC(uint256 _amount) internal returns (uint256 receivedWantTokens) { int128 usdcIndexInPool = int128( int256(uint256(FraxPoolCoinIndexes.USDC)) ); uint256 expectedWantTokensOut = (_amount * receivedWantTokens = curve3PoolZap.remove_liquidity_one_coin( address(fraxPool), _amount, usdcIndexInPool, (expectedWantTokensOut * (MAX_BPS - maxSlippage)) / (MAX_BPS) ); } @dev Provides USDC liquidity on Frax pool on curve to get Lp Tokens @param _amount amount of USDC to deposit to get Lp Tokens @return receivedLpTokens amount of LP tokens received after converting USDC
9,732,571
./full_match/5/0x9dbFE710f0Aa15990ed4783993561c25b8BFE99e/sources/contracts/ERC721ADropsModified.sol
Zombeze Team Wallet
function withdraw() external onlyOwner { uint256 withdrawAmount_100 = (address(this).balance * 100) / 100; payable(0x366159340Ee4Cf5F4475cdDF0E17ED525B2d8F7C).transfer( withdrawAmount_100 ); payable(msg.sender).transfer(address(this).balance); }
1,934,887
pragma solidity ^0.4.18; import 'zeppelin-solidity/contracts/token/ERC20/MintableToken.sol'; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import './Exchange.sol'; /// @title ValexToken /// @author Karim Helmy // Parts sourced from https://github.com/bokkypoobah/Tokens/blob/master/contracts/FixedSupplyToken.sol // ---------------------------------------------------------------------------- // 'VLX' 'Valex Token' token contract // // Symbol : VLX // Name : Valex Token // Total supply: 1,000,000.000000000000000000 // Decimals : 18 // // ---------------------------------------------------------------------------- contract ValexToken is Exchange, StandardToken { using SafeMath for uint; string public name = "Valex Token"; string public symbol = "VLX"; uint8 public decimals = 18; uint256 public initialSupply = 10000 * (10 ** uint256(decimals)); // Voting mappings // Holds what every address has voted for mapping (address => Parameters) voteBook; // Hold frequencies of what addresses have voted for (in coin-votes) mapping (uint => uint) closureFeeFreqs; mapping (uint => uint) cancelFeeFreqs; mapping (uint => uint) cleanSizeFreqs; mapping (uint => uint) minerShareFreqs; // Threshold to be met for each parameter adjustment uint public threshold = (initialSupply / 100) * 51; // How often are you allowed to collect dividends? uint public DISTTIME = 26 weeks; // When were dividends last collected? uint public lastDist = now; // What distribution cycle are we in? uint public distCycle = 0; // How much does one token entitle you to in this cycle? uint public distPerToken = 0; // When did addresses last collect their dividends? mapping (address => uint) lastCollected; /** * @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) { BasicToken.transfer(_to, _value); closureFeeFreqs[voteBook[msg.sender].closureFee] -= _value; cancelFeeFreqs[voteBook[msg.sender].cancelFee] -= _value; cleanSizeFreqs[voteBook[msg.sender].cleanSize] -= _value; minerShareFreqs[voteBook[msg.sender].minerShare] -= _value; if (lastCollected[msg.sender] != distCycle){ collectDividends(msg.sender); } if (lastCollected[_to] != 0 && lastCollected[_to] != distCycle){ collectDividends(_to); } if (lastCollected[_to] == 0){ lastCollected[_to] = lastCollected[msg.sender]; } if (balances[msg.sender] == 0){ lastCollected[msg.sender] = 0; } 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) { StandardToken.transferFrom(_from, _to, _value); closureFeeFreqs[voteBook[_from].closureFee] -= _value; cancelFeeFreqs[voteBook[_from].cancelFee] -= _value; cleanSizeFreqs[voteBook[_from].cleanSize] -= _value; minerShareFreqs[voteBook[_from].minerShare] -= _value; if (lastCollected[_from] != distCycle){ collectDividends(_from); } if (lastCollected[_to] != 0 && lastCollected[_to] != distCycle){ collectDividends(_to); } if (lastCollected[_to] == 0){ lastCollected[_to] = lastCollected[_from]; } if (balances[_from] == 0){ lastCollected[_from] = 0; } return true; } /** * @dev Constructor that gives msg.sender all of existing tokens. * @dev Initializes token to have same parameters as exchange */ function ValexToken(uint closureFee, uint cancelFee, uint cleanSize, uint minershare, bytes32 difficulty) Exchange(closureFee, cancelFee, cleanSize, minershare, difficulty) public { totalSupply_ = initialSupply; balances[msg.sender] = initialSupply; } // Users can collect their dividends on specified time intervals function collectDividends(address _collector) public { require(balances[_collector] > 0); if (lastDist + DISTTIME <= now){ lastDist = now; distCycle += 1; distPerToken = (this.balance - openBalance) / initialSupply; } require(lastCollected[_collector] <= distCycle); _collector.transfer(distPerToken * balances[_collector]); lastCollected[_collector] = distCycle; return; } // Voting functions for various parameters // Solidity doesn't allow any meaningful abstraction // Adjust relevant parameter if threshold met // voting copy3 function voteClosureFee(uint desiredParam) public { require(balances[msg.sender] > 0); require(desiredParam > 0); if (voteBook[msg.sender].closureFee > 0){ closureFeeFreqs[voteBook[msg.sender].closureFee] -= balances[msg.sender]; } voteBook[msg.sender].closureFee = desiredParam; closureFeeFreqs[desiredParam] += balances[msg.sender]; if (closureFeeFreqs[desiredParam] > threshold){ params.closureFee = desiredParam; } } // voting copy3 function voteCancelFee(uint desiredParam) public { require(balances[msg.sender] > 0); require(desiredParam > 0); if (voteBook[msg.sender].cancelFee > 0){ cancelFeeFreqs[voteBook[msg.sender].cancelFee] -= balances[msg.sender]; } voteBook[msg.sender].cancelFee = desiredParam; cancelFeeFreqs[desiredParam] += balances[msg.sender]; if (cancelFeeFreqs[desiredParam] > threshold){ params.cancelFee = desiredParam; } } // voting copy3 function voteCleanSize(uint desiredParam) public { require(balances[msg.sender] > 0); require(desiredParam > 0); if (voteBook[msg.sender].cleanSize > 0){ cleanSizeFreqs[voteBook[msg.sender].cleanSize] -= balances[msg.sender]; } voteBook[msg.sender].cleanSize = desiredParam; cleanSizeFreqs[desiredParam] += balances[msg.sender]; if (cleanSizeFreqs[desiredParam] > threshold){ params.cleanSize = desiredParam; } } // voting copy3 function voteMinerShare(uint desiredParam) public { require(balances[msg.sender] > 0); require(desiredParam > 0); if (voteBook[msg.sender].minerShare > 0){ minerShareFreqs[voteBook[msg.sender].minerShare] -= balances[msg.sender]; } voteBook[msg.sender].minerShare = desiredParam; minerShareFreqs[desiredParam] += balances[msg.sender]; if (minerShareFreqs[desiredParam] > threshold){ params.minerShare = desiredParam; } } // TODO: NEXT VERSION: Implement adding/removing chapters by consensus // TODO: NEXT VERSION: Add vote transferring }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { StandardToken.transferFrom(_from, _to, _value); closureFeeFreqs[voteBook[_from].closureFee] -= _value; cancelFeeFreqs[voteBook[_from].cancelFee] -= _value; cleanSizeFreqs[voteBook[_from].cleanSize] -= _value; minerShareFreqs[voteBook[_from].minerShare] -= _value; if (lastCollected[_from] != distCycle){ collectDividends(_from); } if (lastCollected[_to] != 0 && lastCollected[_to] != distCycle){ collectDividends(_to); } if (lastCollected[_to] == 0){ lastCollected[_to] = lastCollected[_from]; } if (balances[_from] == 0){ lastCollected[_from] = 0; } return true; }
12,861,211
pragma solidity ^0.6.1; pragma experimental ABIEncoderV2; import "./ISellerAdmin.sol"; import "./IAddressRegistry.sol"; import "./IBusinessPartnerStorage.sol"; import "./IPurchasing.sol"; import "./IFunding.sol"; import "./Ownable.sol"; import "./Bindable.sol"; import "./StringConvertible.sol"; /// @title SellerAdmin contract SellerAdmin is ISellerAdmin, Ownable, Bindable, StringConvertible { IAddressRegistry public addressRegistry; IBusinessPartnerStorage public bpStorage; bytes32 public sellerId; constructor (address contractAddressOfRegistry, string memory sellerIdString) public { addressRegistry = IAddressRegistry(contractAddressOfRegistry); sellerId = stringToBytes32(sellerIdString); } // Contract setup function configure(string calldata nameOfBusinessPartnerStorage) onlyOwner() override external { // Lookup address registry to find the global repo for business partners bpStorage = IBusinessPartnerStorage(addressRegistry.getAddressString(nameOfBusinessPartnerStorage)); require(address(bpStorage) != address(0), "Could not find Business Partner Storage contract address in registry"); } // Purchasing /// @notice This function can only be called by the eShop (Purchasing.sol) for the given PO function emitEventForNewPo(IPoTypes.Po calldata po) override external { // Don't trust the PO being passed, use the eShopId to lookup the Purchasing.sol address IPoTypes.Eshop memory eShop = getAndValidateEshop(po.eShopId); require(eShop.purchasingContractAddress == msg.sender, "Function can only be called by eShop"); emit QuoteConvertedToPoLog(po.eShopId, po.quoteId, po.buyerWalletAddress); } function getPo(string calldata eShopIdString, uint poNumber) override external view returns (IPoTypes.Po memory po) { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); return purchasing.getPo(poNumber); } function getPoByEshopIdAndQuote(string calldata eShopIdString, uint quoteId) override external view returns (IPoTypes.Po memory po) { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); return purchasing.getPoByQuote(quoteId); } function setPoItemAccepted(string calldata eShopIdString, uint poNumber, uint8 poItemNumber, bytes32 soNumber, bytes32 soItemNumber) onlyOwner() override external { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemAccepted(poNumber, poItemNumber, soNumber, soItemNumber); } function setPoItemRejected(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) onlyOwner() override external { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemRejected(poNumber, poItemNumber); } function setPoItemReadyForGoodsIssue(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) onlyOwner() override external { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemReadyForGoodsIssue(poNumber, poItemNumber); } function setPoItemGoodsIssued(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) onlyOwner() override external { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemGoodsIssued(poNumber, poItemNumber); } function setPoItemGoodsReceived(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) onlyOwner() override external { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemGoodsReceivedSeller(poNumber, poItemNumber); } function setPoItemCompleted(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) onlyOwner() override external { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemCompleted(poNumber, poItemNumber); } function getAndValidateEshop(bytes32 eShopId) private view returns (IPoTypes.Eshop memory validShop) { IPoTypes.Eshop memory eShop = bpStorage.getEshop(eShopId); require(eShop.purchasingContractAddress != address(0), "eShop has no purchasing address"); require(eShop.quoteSignerCount > 0, "No quote signers found for eShop"); return eShop; } }
Get and validate eShop
function getPoByEshopIdAndQuote(string calldata eShopIdString, uint quoteId) override external view returns (IPoTypes.Po memory po) { bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); return purchasing.getPoByQuote(quoteId); }
7,309,646
pragma solidity >=0.4.22 <0.6.0; import "./GeneralUtilities.sol"; contract FranklinDecentralizedMarketplaceData { // This contract was created, because I needed to create the "addressAssociatedWithMediatorDescription" mapping, and I could not add it in the // FranklinDecentralizedMarketplaceMediation, because when I attempted to deploy the FranklinDecentralizedMarketplaceMediation Contract, the // EVM (Ethereum Virtial Machine) would not lety me due to exceeding number of bytes limit by EVM (Ethereum Virtual Machine). string constant private EMPTY_STRING = ""; // Map that shows whether a Mediated Sales Transaction exists. The "string" key is the Mediated Sales Transaction IPFS Hash. // // Mapping is as follows: // 1) Key: IPFS Hash string of the Mediated Sales Transaction // 2) Value: // A) Boolean value of "true" indicates that the Mediated Sales Transaction exists // B) Boolean value of "false" indicates that the Mediated Sales Transaction exists mapping (string => bool) public mediatedSalesTransactionExists; // This Mapping contains the Description Information about the Mediators. The Mediator is responsible for adding this information. // A Mediator cannot exist without having Description Information, but you can have a Mediator that currently does not exist have a // Description Information. // // Mapping is as follows: // 1) Key: Ethereum Address of the Mediator // 2) Value: IPFS Hash string of the information pertaining to the Mediator. This information is stored in the IPFS Storage Network. // This information should be a JSON-formatted string. mapping(address => string) public descriptionInfoAboutMediators; // This mapping maps the Mediator IPFS Description to the Mediator Address (in string format). This is needed in order to prevent a Mediator // address from using the Mediator IPFS Description of someone else. // // Mapping is as follows: // 1) Key: IPFS Hash string of the information pertaining to the Mediator. This information is stored in the IPFS Storage Network. // This information should be a JSON-formatted string. // 2) Value: Ethereum Address of the Mediator in string format mapping (string => string) public addressAssociatedWithMediatorDescription; // This Mapping contains the Number of Mediations that a Mediator has been involved. // // Mapping is as follows: // 1) Key: Ethereum Address of the Mediator // 2) Value: Number of Mediations that a Mediators has been involved mapping(address => uint) public numberOfMediationsMediatorInvolved; // Map that maps the Mediated Sales Transaction to the Sales Amount in Wei. The "string" key is the Mediated Sales Transaction IPFS Hash. // // Mapping is as follows: // 1) Key: IPFS Hash string of the Mediated Sales Transaction // 2) Value: Amount in Wei that the Buyer chose to pay for the Item(s) mapping (string => uint) public mediatedSalesTransactionAmount; // Map that keeps track of all the Mediated Sales Transactions that an Address has been involved either as a Buyer, Seller, or Mediator. // // Mapping is as follows: // 1) Key: Ethereum Address of the Buyer, Seller, or Mediator // 2) Value: Dynamic Array of string elements where each element is the Mediated Sales Transaction IPFS Hash that uniquely identifies the // Mediated Sales Transaction mapping (address => string[]) public mediatedSalesTransactionsAddressInvolved; // Map that keeps track of whether a Mediated Sales Transaction has been Approved by the Buyer, Seller, and/or Mediator. // The "string" key is the Mediated Sales Transaction IPFS Hash. // // Mapping is as follows: // 1) Key: IPFS Hash string of the Mediated Sales Transaction // 2) Values: // A) address[0] : Boolean flag indicating if Buyer Approves // B) address[1] : Boolean flag indicating if Seller Approves // C) address[2] : Boolean flag indicating if Mediator Approves mapping (string => bool[3]) public mediatedSalesTransactionApprovedByParties; // Map that keeps track of whether a Mediated Sales Transaction has been Disapproved by the Buyer, Seller, and/or Mediator. // The "string" key is the Mediated Sales Transaction IPFS Hash. // // Mapping is as follows: // 1) Key: IPFS Hash string of the Mediated Sales Transaction // 2) Values: // A) address[0] : Boolean flag indicating if Buyer Disapproves // B) address[1] : Boolean flag indicating if Seller Disapproves // C) address[2] : Boolean flag indicating if Mediator Disapproves mapping (string => bool[3]) public mediatedSalesTransactionDisapprovedByParties; address public contractOwner; address public franklinDecentralizedMarketplaceMediationContractAddress; bool public franklinDecentralizedMarketplaceMediationContractAddressHasBeenSet; modifier onlyFranklinDecentralizedMarketplaceMediationContractAddress { require(franklinDecentralizedMarketplaceMediationContractAddressHasBeenSet, "The franklinDecentralizedMarketplaceMediationContractAddress has not been set by contractOwner!"); require(msg.sender == franklinDecentralizedMarketplaceMediationContractAddress, "Only the FranklinDecentralizedMarketplaceMediationContract Address set by the Contract Owner may execute this method!"); _; } constructor() public { contractOwner = msg.sender; } function setFranklinDecentralizedMarketplaceMediationContractAddress(address _franklinDecentralizedMarketplaceMediationContractAddress) public { require(msg.sender == contractOwner, "Only Contract Owner may execute this method!"); require(!franklinDecentralizedMarketplaceMediationContractAddressHasBeenSet, "The franklinDecentralizedMarketplaceMediationContractAddress has alraedy been set!"); franklinDecentralizedMarketplaceMediationContractAddress = _franklinDecentralizedMarketplaceMediationContractAddress; franklinDecentralizedMarketplaceMediationContractAddressHasBeenSet = true; } function setDescriptionInfoAboutMediator(address _mediatorAddress, string memory _mediatorIpfsHashDescription) onlyFranklinDecentralizedMarketplaceMediationContractAddress public { require(!GeneralUtilities._compareStringsEqual(_mediatorIpfsHashDescription, EMPTY_STRING), "Cannot have an empty String for the IPFS Hash Key Description of a Mediator!"); string memory _mediatorAddressString = GeneralUtilities._addressToString(_mediatorAddress); string memory theAddressStringAssociatedWithMediatorDescription = addressAssociatedWithMediatorDescription[_mediatorIpfsHashDescription]; require(GeneralUtilities._compareStringsEqual(theAddressStringAssociatedWithMediatorDescription, EMPTY_STRING) || GeneralUtilities._compareStringsEqual(theAddressStringAssociatedWithMediatorDescription, _mediatorAddressString), "Cannot set a Mediator IPFS Description that has already been associated with another Ethereum Address"); descriptionInfoAboutMediators[_mediatorAddress] = _mediatorIpfsHashDescription; addressAssociatedWithMediatorDescription[_mediatorIpfsHashDescription] = _mediatorAddressString; } function setNumberOfMediationsMediatorInvolved(address _mediatorAddress, uint _numberOfMediations) onlyFranklinDecentralizedMarketplaceMediationContractAddress public { numberOfMediationsMediatorInvolved[_mediatorAddress] = _numberOfMediations; } function setMediatedSalesTransactionAmount(string memory _mediatorIpfsHashDescription, uint _amount) onlyFranklinDecentralizedMarketplaceMediationContractAddress public { mediatedSalesTransactionAmount[_mediatorIpfsHashDescription] = _amount; } // Gets the number of Mediated sales Transactions that the given "_partyAddress" has been involved. function numberOfMediatedSalesTransactionsAddressInvolved(address _partyAddress) external view returns (uint) { return mediatedSalesTransactionsAddressInvolved[_partyAddress].length; } function addMediatedSalesTransactionsAddressInvolved(address _partyAddress, string memory _mediatedSalesTransactionIpfsHash) onlyFranklinDecentralizedMarketplaceMediationContractAddress public { mediatedSalesTransactionsAddressInvolved[_partyAddress].push(_mediatedSalesTransactionIpfsHash); } // Determines if the given "_mediatedSalesTransactionIpfsHash" Mediated Sales Transaction is in the Approved State. It is in the Approved State // if 2-out-of-3 Buyer, Seller, and/or Mediator Approve it. function mediatedSalesTransactionHasBeenApproved(string memory _mediatedSalesTransactionIpfsHash) public view returns (bool) { require(mediatedSalesTransactionExists[_mediatedSalesTransactionIpfsHash], "Given Mediated Sales Transaction IPFS Hash does not exist!"); uint numberOfApprovals = 0; for (uint i = 0; i < 3; i++) { if (mediatedSalesTransactionApprovedByParties[_mediatedSalesTransactionIpfsHash][i]) { numberOfApprovals++; } } return (numberOfApprovals >= 2); } // Determines if the given "_mediatedSalesTransactionIpfsHash" Mediated Sales Transaction is in the Disapprived State. It is in the Disapproved State // if 2-out-of-3 Buyer, Seller, and/or Mediator Disapprove it. function mediatedSalesTransactionHasBeenDisapproved(string memory _mediatedSalesTransactionIpfsHash) public view returns (bool) { require(mediatedSalesTransactionExists[_mediatedSalesTransactionIpfsHash], "Given Mediated Sales Transaction IPFS Hash does not exist!"); uint numberOfDisapprovals = 0; for (uint i = 0; i < 3; i++) { if (mediatedSalesTransactionDisapprovedByParties[_mediatedSalesTransactionIpfsHash][i]) { numberOfDisapprovals++; } } return (numberOfDisapprovals >= 2); } function setMediatedSalesTransactionExistsFlag(string memory _mediatedSalesTransactionIpfsHash, bool _flag) onlyFranklinDecentralizedMarketplaceMediationContractAddress public { mediatedSalesTransactionExists[_mediatedSalesTransactionIpfsHash] = _flag; } function setMediatedSalesTransactionApprovedByPartiesFlag(string memory _mediatedSalesTransactionIpfsHash, uint _indexBuyerSellerOrMediator, bool _flag) onlyFranklinDecentralizedMarketplaceMediationContractAddress public { mediatedSalesTransactionApprovedByParties[_mediatedSalesTransactionIpfsHash][_indexBuyerSellerOrMediator] = _flag; } function setMediatedSalesTransactionDisapprovedByPartiesFlag(string memory _mediatedSalesTransactionIpfsHash, uint _indexBuyerSellerOrMediator, bool _flag) onlyFranklinDecentralizedMarketplaceMediationContractAddress public { mediatedSalesTransactionDisapprovedByParties[_mediatedSalesTransactionIpfsHash][_indexBuyerSellerOrMediator] = _flag; } }
Determines if the given "_mediatedSalesTransactionIpfsHash" Mediated Sales Transaction is in the Approved State. It is in the Approved State if 2-out-of-3 Buyer, Seller, and/or Mediator Approve it.
function mediatedSalesTransactionHasBeenApproved(string memory _mediatedSalesTransactionIpfsHash) public view returns (bool) { require(mediatedSalesTransactionExists[_mediatedSalesTransactionIpfsHash], "Given Mediated Sales Transaction IPFS Hash does not exist!"); uint numberOfApprovals = 0; for (uint i = 0; i < 3; i++) { if (mediatedSalesTransactionApprovedByParties[_mediatedSalesTransactionIpfsHash][i]) { numberOfApprovals++; } } return (numberOfApprovals >= 2); }
942,175
pragma solidity ^0.4.11; // ---------------------------------------------------------------------------- // Safe maths, borrowed from OpenZeppelin // ---------------------------------------------------------------------------- library SafeMath { // ------------------------------------------------------------------------ // Add a number to another number, checking for overflows // ------------------------------------------------------------------------ function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } // ------------------------------------------------------------------------ // Subtract a number from another number, checking for underflows // ------------------------------------------------------------------------ function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { OwnershipTransferred(owner, newOwner); owner = newOwner; } } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals // https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- contract ERC20Token is Owned { using SafeMath for uint; // ------------------------------------------------------------------------ // Total Supply // ------------------------------------------------------------------------ uint256 _totalSupply = 0; // ------------------------------------------------------------------------ // Balances for each account // ------------------------------------------------------------------------ mapping(address => uint256) balances; // ------------------------------------------------------------------------ // Owner of account approves the transfer of an amount to another account // ------------------------------------------------------------------------ mapping(address => mapping (address => uint256)) allowed; // ------------------------------------------------------------------------ // Get the total token supply // ------------------------------------------------------------------------ function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } // ------------------------------------------------------------------------ // Get the account balance of another account with address _owner // ------------------------------------------------------------------------ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer the balance from owner&#39;s account to another account // ------------------------------------------------------------------------ function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount // User has balance && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Allow _spender to withdraw from your account, multiple times, up to the // _value amount. If this function is called again it overwrites the // current allowance with _value. // ------------------------------------------------------------------------ function approve( address _spender, uint256 _amount ) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // ------------------------------------------------------------------------ // Spender of tokens transfer an amount of tokens from the token owner&#39;s // balance to the spender&#39;s account. The owner of the tokens must already // have approve(...)-d this transfer // ------------------------------------------------------------------------ function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount // From a/c has balance && allowed[_from][msg.sender] >= _amount // Transfer approved && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance( address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract DaoCasinoToken is ERC20Token { // ------------------------------------------------------------------------ // Token information // ------------------------------------------------------------------------ string public constant symbol = "BET"; string public constant name = "Dao.Casino"; uint8 public constant decimals = 18; // Do not use `now` here uint256 public STARTDATE; uint256 public ENDDATE; // Cap USD 25mil @ 296.1470 ETH/USD uint256 public CAP; // Cannot have a constant address here - Solidity bug // https://github.com/ethereum/solidity/issues/2441 address public multisig; function DaoCasinoToken(uint256 _start, uint256 _end, uint256 _cap, address _multisig) { STARTDATE = _start; ENDDATE = _end; CAP = _cap; multisig = _multisig; } // > new Date("2017-06-29T13:00:00").getTime()/1000 // 1498741200 uint256 public totalEthers; // ------------------------------------------------------------------------ // Tokens per ETH // Day 1 : 2,000 BET = 1 Ether // Days 2–14 : 1,800 BET = 1 Ether // Days 15–17: 1,700 BET = 1 Ether // Days 18–20: 1,600 BET = 1 Ether // Days 21–23: 1,500 BET = 1 Ether // Days 24–26: 1,400 BET = 1 Ether // Days 27–28: 1,300 BET = 1 Ether // ------------------------------------------------------------------------ function buyPrice() constant returns (uint256) { return buyPriceAt(now); } function buyPriceAt(uint256 at) constant returns (uint256) { if (at < STARTDATE) { return 0; } else if (at < (STARTDATE + 1 days)) { return 2000; } else if (at < (STARTDATE + 15 days)) { return 1800; } else if (at < (STARTDATE + 18 days)) { return 1700; } else if (at < (STARTDATE + 21 days)) { return 1600; } else if (at < (STARTDATE + 24 days)) { return 1500; } else if (at < (STARTDATE + 27 days)) { return 1400; } else if (at <= ENDDATE) { return 1300; } else { return 0; } } // ------------------------------------------------------------------------ // Buy tokens from the contract // ------------------------------------------------------------------------ function () payable { proxyPayment(msg.sender); } // ------------------------------------------------------------------------ // Exchanges can buy on behalf of participant // ------------------------------------------------------------------------ function proxyPayment(address participant) payable { // No contributions before the start of the crowdsale require(now >= STARTDATE); // No contributions after the end of the crowdsale require(now <= ENDDATE); // No 0 contributions require(msg.value > 0); // Add ETH raised to total totalEthers = totalEthers.add(msg.value); // Cannot exceed cap require(totalEthers <= CAP); // What is the BET to ETH rate uint256 _buyPrice = buyPrice(); // Calculate #BET - this is safe as _buyPrice is known // and msg.value is restricted to valid values uint tokens = msg.value * _buyPrice; // Check tokens > 0 require(tokens > 0); // Compute tokens for foundation 30% // Number of tokens restricted so maths is safe uint multisigTokens = tokens * 3 / 7; // Add to total supply _totalSupply = _totalSupply.add(tokens); _totalSupply = _totalSupply.add(multisigTokens); // Add to balances balances[participant] = balances[participant].add(tokens); balances[multisig] = balances[multisig].add(multisigTokens); // Log events TokensBought(participant, msg.value, totalEthers, tokens, multisigTokens, _totalSupply, _buyPrice); Transfer(0x0, participant, tokens); Transfer(0x0, multisig, multisigTokens); // Move the funds to a safe wallet multisig.transfer(msg.value); } event TokensBought(address indexed buyer, uint256 ethers, uint256 newEtherBalance, uint256 tokens, uint256 multisigTokens, uint256 newTotalSupply, uint256 buyPrice); // ------------------------------------------------------------------------ // Owner to add precommitment funding token balance before the crowdsale // commences // ------------------------------------------------------------------------ function addPrecommitment(address participant, uint balance) onlyOwner { require(now < STARTDATE); require(balance > 0); balances[participant] = balances[participant].add(balance); _totalSupply = _totalSupply.add(balance); Transfer(0x0, participant, balance); } // ------------------------------------------------------------------------ // Transfer the balance from owner&#39;s account to another account, with a // check that the crowdsale is finalised // ------------------------------------------------------------------------ function transfer(address _to, uint _amount) returns (bool success) { // Cannot transfer before crowdsale ends or cap reached require(now > ENDDATE || totalEthers == CAP); // Standard transfer return super.transfer(_to, _amount); } // ------------------------------------------------------------------------ // Spender of tokens transfer an amount of tokens from the token owner&#39;s // balance to another account, with a check that the crowdsale is // finalised // ------------------------------------------------------------------------ function transferFrom(address _from, address _to, uint _amount) returns (bool success) { // Cannot transfer before crowdsale ends or cap reached require(now > ENDDATE || totalEthers == CAP); // Standard transferFrom return super.transferFrom(_from, _to, _amount); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner returns (bool success) { return ERC20Token(tokenAddress).transfer(owner, amount); } } library CreatorDaoCasinoToken { function create(uint256 _start, uint256 _end, uint256 _cap, address _multisig) returns (DaoCasinoToken) { return new DaoCasinoToken(_start, _end, _cap, _multisig); } function version() constant returns (string) { return "v0.6.3"; } }
------------------------------------------------------------------------ Exchanges can buy on behalf of participant ------------------------------------------------------------------------ No contributions before the start of the crowdsale No contributions after the end of the crowdsale No 0 contributions Add ETH raised to total Cannot exceed cap What is the BET to ETH rate Calculate BET - this is safe as _buyPrice is known and msg.value is restricted to valid values Check tokens > 0 Compute tokens for foundation 30% Number of tokens restricted so maths is safe Add to total supply Add to balances Log events Move the funds to a safe wallet
function proxyPayment(address participant) payable { require(now >= STARTDATE); require(now <= ENDDATE); require(msg.value > 0); totalEthers = totalEthers.add(msg.value); require(totalEthers <= CAP); uint256 _buyPrice = buyPrice(); uint tokens = msg.value * _buyPrice; require(tokens > 0); uint multisigTokens = tokens * 3 / 7; _totalSupply = _totalSupply.add(tokens); _totalSupply = _totalSupply.add(multisigTokens); balances[participant] = balances[participant].add(tokens); balances[multisig] = balances[multisig].add(multisigTokens); TokensBought(participant, msg.value, totalEthers, tokens, multisigTokens, _totalSupply, _buyPrice); Transfer(0x0, participant, tokens); Transfer(0x0, multisig, multisigTokens); multisig.transfer(msg.value); } event TokensBought(address indexed buyer, uint256 ethers, uint256 newEtherBalance, uint256 tokens, uint256 multisigTokens, uint256 newTotalSupply, uint256 buyPrice);
6,752,997
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol
Search the list of gTokens and selects the one for which the withdrawal will provide the best correction of deviation from its target share. _reserveAmount The total reserve amount used for calculation. return _adjustToken The gToken to withdraw from. return _adjustAmount The amount to be withdrawn./
function _findWithdrawal(Self storage _self, uint256 _reserveAmount) internal view returns (address _adjustToken, uint256 _adjustAmount) { uint256 _maxPercent = _self.portfolioRebalanceMargin; _adjustToken = address(0); _adjustAmount = 0; uint256 _tokenCount = _self.tokens.length(); for (uint256 _index = 0; _index < _tokenCount; _index++) { address _token = _self.tokens.at(_index); uint256 _oldTokenReserve = _self._getUnderlyingReserve(_token); uint256 _oldTokenPercent = _oldTokenReserve.mul(1e18).div(_reserveAmount); uint256 _newTokenPercent = _self.percents[_token]; if (_newTokenPercent < _oldTokenPercent) { uint256 _percent = _oldTokenPercent.sub(_newTokenPercent); if (_percent > _maxPercent) { uint256 _newTokenReserve = _reserveAmount.mul(_newTokenPercent).div(1e18); uint256 _amount = _oldTokenReserve.sub(_newTokenReserve); _maxPercent = _percent; _adjustToken = _token; _adjustAmount = _amount; } } } return (_adjustToken, _adjustAmount); }
2,650,981
./full_match/44787/0xe13BE8c7bfCf6ccA65A96D7a91f8482D712CB330/sources/project_/contracts/ERC20Project.sol
Ownable methods overridden
function transferOwnership( address newOwner ) public override onlyOwner { require( newOwner != address(0), "Ownable: new owner cannot be the zero address" ); _transferOwnership(newOwner); }
13,262,668
/** *Submitted for verification at Etherscan.io on 2021-05-14 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @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, uint 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 (uint); /** * @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, uint 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, uint 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, uint 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, uint value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint a, uint b) internal pure returns (bool, uint) { uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (bool, uint) { 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(uint a, uint b) internal pure returns (uint) { uint 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { 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( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @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. uint 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, uint 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, uint 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, uint value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @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, uint 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, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/protocol/IStrategyERC20_V3.sol /* version 1.3.0 Changes listed here do not affect interaction with other contracts (Vault and Controller) - remove functions that are not called by other contracts (vaults and controller) */ interface IStrategyERC20_V3 { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying token (ETH or ERC20) @dev Return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy */ function underlying() external view returns (address); /* @notice Returns total amount of underlying token transferred from vault */ function totalDebt() external view returns (uint); /* @notice Returns amount of underlying token locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying token is invested */ function totalAssets() external view returns (uint); /* @notice Deposit `amount` underlying token @param amount Amount of underlying token to deposit */ function deposit(uint _amount) external; /* @notice Withdraw `_amount` underlying token @param amount Amount of underlying token to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying token from strategy */ function withdrawAll() external; /* @notice Sell any staking rewards for underlying */ function harvest() external; /* @notice Increase total debt if totalAssets > totalDebt */ function skim() external; /* @notice Exit from strategy, transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer @dev _token must not be equal to underlying token */ function sweep(address _token) external; } // File: contracts/StrategyERC20_V3.sol /* Changes - remove functions related to slippage and delta - add keeper - remove _increaseDebt - remove _decreaseDebt */ // used inside harvest abstract contract StrategyERC20_V3 is IStrategyERC20_V3 { using SafeERC20 for IERC20; using SafeMath for uint; address public override admin; address public nextAdmin; address public override controller; address public immutable override vault; address public immutable override underlying; // some functions specific to strategy cannot be called by controller // so we introduce a new role address public keeper; // total amount of underlying transferred from vault uint public override totalDebt; // performance fee sent to treasury when harvest() generates profit uint public performanceFee = 500; uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee uint internal constant PERFORMANCE_FEE_MAX = 10000; // Force exit, in case normal exit fails bool public forceExit; constructor( address _controller, address _vault, address _underlying, address _keeper ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); require(_keeper != address(0), "keeper = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; keeper = _keeper; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault || msg.sender == keeper, "!authorized" ); _; } function setNextAdmin(address _nextAdmin) external onlyAdmin { require(_nextAdmin != admin, "next admin = current"); // allow next admin = zero address (cancel next admin) nextAdmin = _nextAdmin; } function acceptAdmin() external { require(msg.sender == nextAdmin, "!next admin"); admin = msg.sender; nextAdmin = address(0); } function setController(address _controller) external onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setKeeper(address _keeper) external onlyAdmin { require(_keeper != address(0), "keeper = zero address"); keeper = _keeper; } function setPerformanceFee(uint _fee) external onlyAdmin { require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap"); performanceFee = _fee; } function setForceExit(bool _forceExit) external onlyAdmin { forceExit = _forceExit; } function totalAssets() external view virtual override returns (uint); function deposit(uint) external virtual override; function withdraw(uint) external virtual override; function withdrawAll() external virtual override; function harvest() external virtual override; function skim() external virtual override; function exit() external virtual override; function sweep(address) external virtual override; } // File: contracts/interfaces/uniswap/Uniswap.sol interface Uniswap { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactTokensForETH( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File: contracts/interfaces/compound/CErc20.sol interface CErc20 { function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function redeem(uint) external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function balanceOfUnderlying(address account) external returns (uint); function getAccountSnapshot(address account) external view returns ( uint, uint, uint, uint ); } // File: contracts/interfaces/compound/Comptroller.sol interface Comptroller { function markets(address cToken) external view returns ( bool, uint, bool ); // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; } // File: contracts/strategies/StrategyCompLev.sol /* APY estimate c = collateral ratio i_s = supply interest rate (APY) i_b = borrow interest rate (APY) c_s = supply COMP reward (APY) c_b = borrow COMP reward (APY) leverage APY = 1 / (1 - c) * (i_s + c_s - c * (i_b - c_b)) plugging some numbers 31.08 = 4 * (7.01 + 4 - 0.75 * (9.08 - 4.76)) */ /* State transitions and valid transactions ### State ### buff = buffer s = supplied b = borrowed ### Transactions ### dl = deleverage l = leverage w = withdraw d = deposit s(x) = set butter to x ### State Transitions ### s(max) (buf = max, s > 0, b > 0) <--------- (buf = min, s > 0, b > 0) | | ^ | dl, w | dl, w | l, d | | | V V | (buf = max, s > 0, b = 0) ---------> (buf = min, s > 0, b = 0) s(min) */ contract StrategyCompLev is StrategyERC20_V3 { event Deposit(uint amount); event Withdraw(uint amount); event Harvest(uint profit); event Skim(uint profit); // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Compound // address private constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address private constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address private immutable cToken; // buffer to stay below market collateral ratio, scaled up by 1e18 uint public buffer = 0.04 * 1e18; constructor( address _controller, address _vault, address _underlying, address _cToken, address _keeper ) public StrategyERC20_V3(_controller, _vault, _underlying, _keeper) { require(_cToken != address(0), "cToken = zero address"); cToken = _cToken; IERC20(_underlying).safeApprove(_cToken, type(uint).max); // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(COMP).safeApprove(UNISWAP, type(uint).max); } function _increaseDebt(uint _amount) private returns (uint) { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(vault, address(this), _amount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balAfter.sub(balBefore); totalDebt = totalDebt.add(diff); return diff; } function _decreaseDebt(uint _amount) private returns (uint) { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, _amount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balBefore.sub(balAfter); if (diff >= totalDebt) { totalDebt = 0; } else { totalDebt -= diff; } return diff; } function _totalAssets() private view returns (uint) { // WARNING: This returns balance last time someone transacted with cToken (uint error, uint cTokenBal, uint borrowed, uint exchangeRate) = CErc20(cToken).getAccountSnapshot(address(this)); if (error > 0) { // something is wrong, return 0 return 0; } uint supplied = cTokenBal.mul(exchangeRate) / 1e18; if (supplied < borrowed) { // something is wrong, return 0 return 0; } uint bal = IERC20(underlying).balanceOf(address(this)); // supplied >= borrowed return bal.add(supplied - borrowed); } /* @notice Returns amount of underlying tokens locked in this contract */ function totalAssets() external view override returns (uint) { return _totalAssets(); } /* @dev buffer = 0 means safe collateral ratio = market collateral ratio buffer = 1e18 means safe collateral ratio = 0 */ function setBuffer(uint _buffer) external onlyAuthorized { require(_buffer > 0 && _buffer <= 1e18, "buffer"); buffer = _buffer; } function _getMarketCollateralRatio() private view returns (uint) { /* This can be changed by Compound Governance, with a minimum waiting period of five days */ (, uint col, ) = Comptroller(COMPTROLLER).markets(cToken); return col; } function _getSafeCollateralRatio(uint _marketCol) private view returns (uint) { if (_marketCol > buffer) { return _marketCol - buffer; } return 0; } // Not view function function _getSupplied() private returns (uint) { return CErc20(cToken).balanceOfUnderlying(address(this)); } // Not view function function _getBorrowed() private returns (uint) { return CErc20(cToken).borrowBalanceCurrent(address(this)); } // Not view function. Call using static call from web3 function getLivePosition() external returns ( uint supplied, uint borrowed, uint marketCol, uint safeCol ) { supplied = _getSupplied(); borrowed = _getBorrowed(); marketCol = _getMarketCollateralRatio(); safeCol = _getSafeCollateralRatio(marketCol); } // @dev This returns balance last time someone transacted with cToken function getCachedPosition() external view returns ( uint supplied, uint borrowed, uint marketCol, uint safeCol ) { // ignore first output, which is error code (, uint cTokenBal, uint _borrowed, uint exchangeRate) = CErc20(cToken).getAccountSnapshot(address(this)); supplied = cTokenBal.mul(exchangeRate) / 1e18; borrowed = _borrowed; marketCol = _getMarketCollateralRatio(); safeCol = _getSafeCollateralRatio(marketCol); } // @dev This modifier checks collateral ratio after leverage or deleverage modifier checkCollateralRatio() { _; uint supplied = _getSupplied(); uint borrowed = _getBorrowed(); uint marketCol = _getMarketCollateralRatio(); uint safeCol = _getSafeCollateralRatio(marketCol); // borrowed / supplied <= safe col // supplied can = 0 so we check borrowed <= supplied * safe col // max borrow uint max = supplied.mul(safeCol) / 1e18; require(borrowed <= max, "borrowed > max"); } // @dev In case infinite approval is reduced so that strategy cannot function function approve(uint _amount) external onlyAdmin { IERC20(underlying).safeApprove(cToken, _amount); } function _supply(uint _amount) private { require(CErc20(cToken).mint(_amount) == 0, "mint"); } // @dev Execute manual recovery by admin // @dev `_amount` must be >= balance of underlying function supply(uint _amount) external onlyAdmin { _supply(_amount); } function _borrow(uint _amount) private { require(CErc20(cToken).borrow(_amount) == 0, "borrow"); } // @dev Execute manual recovery by admin function borrow(uint _amount) external onlyAdmin { _borrow(_amount); } function _repay(uint _amount) private { require(CErc20(cToken).repayBorrow(_amount) == 0, "repay"); } // @dev Execute manual recovery by admin // @dev `_amount` must be >= balance of underlying function repay(uint _amount) external onlyAdmin { _repay(_amount); } function _redeem(uint _amount) private { require(CErc20(cToken).redeemUnderlying(_amount) == 0, "redeem"); } // @dev Execute manual recovery by admin function redeem(uint _amount) external onlyAdmin { _redeem(_amount); } function _getMaxLeverageRatio(uint _col) private pure returns (uint) { /* c = collateral ratio geometric series converges to 1 / (1 - c) */ // multiplied by 1e18 return uint(1e36).div(uint(1e18).sub(_col)); } function _getBorrowAmount( uint _supplied, uint _borrowed, uint _col ) private pure returns (uint) { /* c = collateral ratio s = supplied b = borrowed x = amount to borrow (b + x) / s <= c becomes x <= sc - b */ // max borrow uint max = _supplied.mul(_col) / 1e18; if (_borrowed >= max) { return 0; } return max - _borrowed; } /* Find total supply S_n after n iterations starting with S_0 supplied and B_0 borrowed c = collateral ratio S_i = supplied after i iterations B_i = borrowed after i iterations S_0 = current supplied B_0 = current borrowed borrowed and supplied after n iterations B_n = cS_(n-1) S_n = S_(n-1) + (cS_(n-1) - B_(n-1)) you can prove using algebra and induction that B_n / S_n <= c S_n - S_(n-1) = c^(n-1) * (cS_0 - B_0) S_n = S_0 + sum (c^i * (cS_0 - B_0)), 0 <= i <= n - 1 = S_0 + (1 - c^n) / (1 - c) S_n <= S_0 + (cS_0 - B_0) / (1 - c) */ function _leverage(uint _targetSupply) private checkCollateralRatio { // buffer = 1e18 means safe collateral ratio = 0 if (buffer >= 1e18) { return; } uint supplied = _getSupplied(); uint borrowed = _getBorrowed(); uint unleveraged = supplied.sub(borrowed); // supply with 0 leverage require(_targetSupply >= unleveraged, "leverage"); uint marketCol = _getMarketCollateralRatio(); uint safeCol = _getSafeCollateralRatio(marketCol); uint lev = _getMaxLeverageRatio(safeCol); // 99% to be safe, and save gas uint max = (unleveraged.mul(lev) / 1e18).mul(9900) / 10000; if (_targetSupply >= max) { _targetSupply = max; } uint i; while (supplied < _targetSupply) { // target is usually reached in 9 iterations require(i < 25, "max iteration"); // use market collateral to calculate borrow amount // this is done so that supplied can reach _targetSupply // 99.99% is borrowed to be safe uint borrowAmount = _getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000; require(borrowAmount > 0, "borrow = 0"); if (supplied.add(borrowAmount) > _targetSupply) { // borrow > 0 since supplied < _targetSupply borrowAmount = _targetSupply.sub(supplied); } _borrow(borrowAmount); // end loop with _supply, this ensures no borrowed amount is unutilized _supply(borrowAmount); // supplied > _getSupplied(), by about 3 * 1e12 %, but we use local variable to save gas supplied = supplied.add(borrowAmount); // _getBorrowed == borrowed borrowed = borrowed.add(borrowAmount); i++; } } function leverage(uint _targetSupply) external onlyAuthorized { _leverage(_targetSupply); } function _deposit() private { uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { _supply(bal); // leverage to max _leverage(type(uint).max); } } /* @notice Deposit underlying token into this strategy @param _amount Amount of underlying token to deposit */ function deposit(uint _amount) external override onlyAuthorized { require(_amount > 0, "deposit = 0"); uint diff = _increaseDebt(_amount); _deposit(); emit Deposit(diff); } function _getRedeemAmount( uint _supplied, uint _borrowed, uint _col ) private pure returns (uint) { /* c = collateral ratio s = supplied b = borrowed r = redeem b / (s - r) <= c becomes r <= s - b / c */ // min supply // b / c = min supply needed to borrow b uint min = _borrowed.mul(1e18).div(_col); if (_supplied <= min) { return 0; } return _supplied - min; } /* Find S_0, amount of supply with 0 leverage, after n iterations starting with S_n supplied and B_n borrowed c = collateral ratio S_n = current supplied B_n = current borrowed S_(n-i) = supplied after i iterations B_(n-i) = borrowed after i iterations R_(n-i) = Redeemable after i iterations = S_(n-i) - B_(n-i) / c where B_(n-i) / c = min supply needed to borrow B_(n-i) For 0 <= k <= n - 1 S_k = S_(k+1) - R_(k+1) B_k = B_(k+1) - R_(k+1) and S_k - B_k = S_(k+1) - B_(k+1) so S_0 - B_0 = S_1 - S_2 = ... = S_n - B_n S_0 has 0 leverage so B_0 = 0 and we get S_0 = S_0 - B_0 = S_n - B_n ------------------------------------------ Find S_(n-k), amount of supply, after k iterations starting with S_n supplied and B_n borrowed with algebra and induction you can derive that R_(n-k) = R_n / c^k S_(n-k) = S_n - sum R_(n-i), 0 <= i <= k - 1 = S_n - R_n * ((1 - 1/c^k) / (1 - 1/c)) Equation above is valid for S_(n - k) k < n */ function _deleverage(uint _targetSupply) private checkCollateralRatio { uint supplied = _getSupplied(); uint borrowed = _getBorrowed(); uint unleveraged = supplied.sub(borrowed); require(_targetSupply <= supplied, "deleverage"); uint marketCol = _getMarketCollateralRatio(); // min supply if (_targetSupply <= unleveraged) { _targetSupply = unleveraged; } uint i; while (supplied > _targetSupply) { // target is usually reached in 8 iterations require(i < 25, "max iteration"); // 99.99% to be safe uint redeemAmount = (_getRedeemAmount(supplied, borrowed, marketCol)).mul(9999) / 10000; require(redeemAmount > 0, "redeem = 0"); if (supplied.sub(redeemAmount) < _targetSupply) { // redeem > 0 since supplied > _targetSupply redeemAmount = supplied.sub(_targetSupply); } _redeem(redeemAmount); _repay(redeemAmount); // supplied < _geSupplied(), by about 7 * 1e12 % supplied = supplied.sub(redeemAmount); // borrowed == _getBorrowed() borrowed = borrowed.sub(redeemAmount); i++; } } function deleverage(uint _targetSupply) external onlyAuthorized { _deleverage(_targetSupply); } // @dev Returns amount available for transfer function _withdraw(uint _amount) private returns (uint) { uint bal = IERC20(underlying).balanceOf(address(this)); if (bal >= _amount) { return _amount; } uint redeemAmount = _amount - bal; /* c = collateral ratio s = supplied b = borrowed r = amount to redeem x = amount to repay where r <= s - b (can't redeem more than unleveraged supply) and x <= b (can't repay more than borrowed) and (b - x) / (s - x - r) <= c (stay below c after redeem and repay) so pick x such that (b - cs + cr) / (1 - c) <= x <= b when b <= cs left side of equation above <= cr / (1 - c) so pick x such that cr / (1 - c) <= x <= b */ uint supplied = _getSupplied(); uint borrowed = _getBorrowed(); uint marketCol = _getMarketCollateralRatio(); uint safeCol = _getSafeCollateralRatio(marketCol); uint unleveraged = supplied.sub(borrowed); // r <= s - b if (redeemAmount > unleveraged) { redeemAmount = unleveraged; } // cr / (1 - c) <= x <= b uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol)); if (repayAmount > borrowed) { repayAmount = borrowed; } _deleverage(supplied.sub(repayAmount)); _redeem(redeemAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); if (balAfter < _amount) { return balAfter; } return _amount; } /* @notice Withdraw undelying token to vault @param _amount Amount of underlying token to withdraw @dev Caller should implement guard against slippage */ function withdraw(uint _amount) external override onlyAuthorized { require(_amount > 0, "withdraw = 0"); // available <= _amount uint available = _withdraw(_amount); uint diff; if (available > 0) { diff = _decreaseDebt(available); } emit Withdraw(diff); } // @dev withdraw all creates dust in supplied function _withdrawAll() private { _withdraw(type(uint).max); // In case there is dust, re-calculate balance uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { IERC20(underlying).safeTransfer(vault, bal); totalDebt = 0; } emit Withdraw(bal); } /* @notice Withdraw all underlying to vault @dev Caller should implement guard agains slippage */ function withdrawAll() external override onlyAuthorized { _withdrawAll(); } /* @dev Uniswap fails with zero address so no check is necessary here */ function _swap( address _from, address _to, uint _amount ) private { // create dynamic array with 3 elements address[] memory path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; Uniswap(UNISWAP).swapExactTokensForTokens( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards() private { // claim COMP address[] memory cTokens = new address[](1); cTokens[0] = cToken; Comptroller(COMPTROLLER).claimComp(address(this), cTokens); uint compBal = IERC20(COMP).balanceOf(address(this)); if (compBal > 0) { _swap(COMP, underlying, compBal); // Now this contract has underlying token } } /* @notice Claim and sell any rewards */ function harvest() external override onlyAuthorized { _claimRewards(); uint bal = IERC20(underlying).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(underlying).safeTransfer(treasury, fee); } // _supply() to decrease collateral ratio and earn interest // use _supply() instead of _deposit() to save gas uint profit = bal.sub(fee); _supply(profit); emit Harvest(profit); } } /* @notice Increase total debt if profit > 0 */ function skim() external override onlyAuthorized { uint bal = IERC20(underlying).balanceOf(address(this)); uint supplied = _getSupplied(); uint borrowed = _getBorrowed(); uint unleveraged = supplied.sub(borrowed); uint total = bal.add(unleveraged); require(total > totalDebt, "total <= debt"); uint profit = total - totalDebt; // Incrementing totalDebt has the same effect as transferring profit // back to vault and then depositing into this strategy // Here we simply increment totalDebt to save gas totalDebt = total; emit Skim(profit); } /* @notice Exit from strategy, transfer all underlying tokens back to vault unless forceExit = true */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(); _withdrawAll(); } /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer */ function sweep(address _token) external override onlyAdmin { require(_token != underlying, "protected token"); require(_token != cToken, "protected token"); require(_token != COMP, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // File: contracts/strategies/StrategyCompLevDai.sol contract StrategyCompLevDai is StrategyCompLev { constructor( address _controller, address _vault, address _cToken, address _keeper ) public StrategyCompLev( _controller, _vault, // DAI 0x6B175474E89094C44Da98b954EedeAC495271d0F, // CDAI _cToken, _keeper ) {} }
/ buffer = 1e18 means safe collateral ratio = 0 target is usually reached in 9 iterations use market collateral to calculate borrow amount this is done so that supplied can reach _targetSupply 99.99% is borrowed to be safe borrow > 0 since supplied < _targetSupply
function _leverage(uint _targetSupply) private checkCollateralRatio { if (buffer >= 1e18) { return; } uint supplied = _getSupplied(); uint borrowed = _getBorrowed(); require(_targetSupply >= unleveraged, "leverage"); uint marketCol = _getMarketCollateralRatio(); uint safeCol = _getSafeCollateralRatio(marketCol); uint lev = _getMaxLeverageRatio(safeCol); if (_targetSupply >= max) { _targetSupply = max; } uint i; while (supplied < _targetSupply) { require(i < 25, "max iteration"); uint borrowAmount = _getBorrowAmount(supplied, borrowed, marketCol).mul(9999) / 10000; require(borrowAmount > 0, "borrow = 0"); if (supplied.add(borrowAmount) > _targetSupply) { borrowAmount = _targetSupply.sub(supplied); } _borrow(borrowAmount); i++; } }
2,239,315
pragma solidity >=0.4.0; contract Contest { //Creating structure to model the contestant struct Contestant { uint id; string name; uint voteCount; } constructor () public { addContestant("Tom"); addContestant("Jerry"); } /** * use mapping to get or fetch the contestant details * this is like * contestant[1] => 1,tom,0 * contestant[2] => 2,jerry,0 * */ mapping(uint => Contestant) public contestants; //to save the list of voters already voted. mapping(address => bool) public voters; /** * Public state variable to keep track of contestant count * in other language we can find the length of contestants by len(contestants) * but in blockchain this will return * contanstant[?] = "0,"",0 * So we have to keep track of contestants when the are added. * */ uint public contestantsCount; event votedEvent( uint indexed _contestantId ); /** * Function to add Contestant * */ function addContestant (string memory _name) private { contestantsCount++; contestants[contestantsCount] = Contestant(contestantsCount, _name, 0); } function vote(uint _contestantId) public { require(!voters[msg.sender]); require(_contestantId > 0 && _contestantId <= contestantsCount); //increase the vote count of particular contestant contestants[_contestantId].voteCount++; //set the voter voted status to true. voters[msg.sender] = true; emit votedEvent(_contestantId); } }
increase the vote count of particular contestantset the voter voted status to true.
function vote(uint _contestantId) public { require(!voters[msg.sender]); require(_contestantId > 0 && _contestantId <= contestantsCount); contestants[_contestantId].voteCount++; voters[msg.sender] = true; emit votedEvent(_contestantId); }
5,419,988
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./OpenOraclePriceData.sol"; import "./OpenOracleView.sol"; import "./OpenOracleOnChainInterface.sol"; /** * @notice The DelFi Price Feed View * @author Compound Labs, Inc. */ contract DelFiPriceWithOnchainData is OpenOracleView { /** * @notice The fundamental unit of storage for the on-chain source */ struct Datum { uint64 timestamp; uint64 value; } mapping(address => mapping(string => Datum)) private onChainData; /** * @notice The list(array) of onChainSources contract addresses */ address[] onChainSources; uint public duration; //how long prices are good for /** * @notice The mapping of medianized prices per symbol */ mapping(string => uint64) public prices; /** * @notice The event emitted when a price is written to storage */ event Price(string symbol, uint64 price); /** * @notice Specify the OpenOraclePriceData address, addresses for approved off-chain and on-chain data providers. * @param data_ is the address for the OpenOraclePriceData contract * @param sources_ is the list of authorized addresses to provide/sign off-chain data * @param onChainSources_ is the list of authorized on-chain souces addresses * @param _duration is the timeframe a value is considered a good value. Basically sets an expiration date * for a value to be "good for use" from when a value is added to when is used. */ constructor(OpenOraclePriceData data_, address[] memory sources_,address[] memory onChainSources_, uint _duration) public OpenOracleView(data_, sources_) { onChainSources = onChainSources_; duration = _duration; } /** * @notice Allows users to get median price data * @param _symbol The symbol/identifier for data such as "ETH/USD" */ function getPrice(string memory _symbol) public view returns(uint64){ return prices[_symbol]; } /** * @notice Primary entry point to post and recalculate prices * @dev We let anyone pay to post anything, but only sources count for prices. * @param messages The messages to post to the oracle * @param signatures The signatures for the corresponding messages * @param symbols The symbol/identifier for data such as "ETH/USD" */ function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external { require(messages.length == signatures.length, "messages and signatures must be 1:1"); // Post the messages, whatever they are for (uint ii = 0; ii < messages.length; ii++) { OpenOraclePriceData(address(data)).put(messages[ii], signatures[ii]); } for (uint k = 0; k < symbols.length; k++) { string memory symbol = symbols[k]; updateOnChainPrice(symbol); uint64 price = medianPrice(symbol); prices[symbol] = price; emit Price(symbol, price); } } /** * @notice Saves median of on-chain and off-chain oracle data for the specified symbols * @param symbols The symbols/identifiers for data such as "ETH/USD" */ function postOnChainPrices(string[] memory symbols) public { for (uint i = 0; i < symbols.length; i++) { string memory symbol = symbols[i]; updateOnChainPrice(symbol); uint64 price = medianPrice(symbol); prices[symbol] = price; emit Price(symbol, price); } } /** * notice Gets off-chain oracle data for the specified symbol * @param symbol The symbol/identifier for data such as "ETH/USD" */ function updateOnChainPrice(string memory symbol) internal { bool _didGet; uint _retrievedValue; uint _timestampRetrieved; for(uint j=0; j< onChainSources.length; j++){ (_didGet,_retrievedValue,_timestampRetrieved) = OpenOracleOnChainInterface(address(onChainSources[j])).getCurrentValue(symbol); if(_didGet){//or a different threshold ( && _timestampRetrieved > now - 1 days .. or none like Compound) onChainData[onChainSources[j]][symbol] = Datum({ value: uint64(_retrievedValue), timestamp: uint64(_timestampRetrieved) }); } } } /** * @notice Calculates the median price over any set of sources * @param symbol The symbol to calculate the median price of * @return median The median price over the set of sources */ function medianPrice(string memory symbol) public returns (uint64 median) { // Calculate the median price, write to storage, and emit an event //we need to have a timestamp restriction (updated within last X...) uint64[] memory postedPrices = new uint64[](sources.length + onChainSources.length); uint64 _t; uint64 _v; uint _updatedSources; for (uint i = 0; i <sources.length + onChainSources.length; i++){ if(i < sources.length){ (_t,_v) = OpenOraclePriceData(address(data)).get(sources[i], symbol); if (_t > now - duration){ postedPrices[_updatedSources] =_v; _updatedSources++; } } else{ (_t,_v) = getOnChain(onChainSources[i-sources.length], symbol); if (_t > now - duration){ postedPrices[_updatedSources] = _v; _updatedSources++; } } } //resize array for sorting uint64[] memory allPrices = new uint64[](_updatedSources); for (uint i=0; i < (_updatedSources); i++) { allPrices[i] = postedPrices[i]; } uint64[] memory sortedPrices = sort(allPrices); if(_updatedSources>1){ return sortedPrices[_updatedSources / 2]; } else if(_updatedSources == 1){ return sortedPrices[0]; } else{ return 0; } } /** * @notice Helper to sort an array of uints * @param array Array of integers to sort * @return The sorted array of integers */ function sort(uint64[] memory array) private pure returns (uint64[] memory) { uint N = array.length; for (uint i = 0; i < N; i++) { for (uint j = i + 1; j < N; j++) { if (array[i] > array[j]) { uint64 tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } } return array; } /** * @notice Read a single key from an authenticated source * @param source The verifiable author of the data * @param key The selector for the value to return * @return The claimed Unix timestamp for the data and the price value (defaults to (0, 0)) */ function getOnChain(address source, string memory key) public view returns (uint64, uint64) { Datum storage datum = onChainData[source][key]; return (datum.timestamp, datum.value); } /** * @notice Read only the value for a single key from an authenticated source * @param source The verifiable author of the data * @param key The selector for the value to return * @return The price value (defaults to 0) */ function getOnChainPrice(address source, string calldata key) external view returns (uint64) { return onChainData[source][key].value; } }
Calculates the median price over any set of sources symbol The symbol to calculate the median price of return median The median price over the set of sources/ Calculate the median price, write to storage, and emit an eventwe need to have a timestamp restriction (updated within last X...)
function medianPrice(string memory symbol) public returns (uint64 median) { uint64[] memory postedPrices = new uint64[](sources.length + onChainSources.length); uint64 _t; uint64 _v; uint _updatedSources; for (uint i = 0; i <sources.length + onChainSources.length; i++){ if(i < sources.length){ (_t,_v) = OpenOraclePriceData(address(data)).get(sources[i], symbol); if (_t > now - duration){ postedPrices[_updatedSources] =_v; _updatedSources++; } } else{ (_t,_v) = getOnChain(onChainSources[i-sources.length], symbol); if (_t > now - duration){ postedPrices[_updatedSources] = _v; _updatedSources++; } } } for (uint i = 0; i <sources.length + onChainSources.length; i++){ if(i < sources.length){ (_t,_v) = OpenOraclePriceData(address(data)).get(sources[i], symbol); if (_t > now - duration){ postedPrices[_updatedSources] =_v; _updatedSources++; } } else{ (_t,_v) = getOnChain(onChainSources[i-sources.length], symbol); if (_t > now - duration){ postedPrices[_updatedSources] = _v; _updatedSources++; } } } for (uint i = 0; i <sources.length + onChainSources.length; i++){ if(i < sources.length){ (_t,_v) = OpenOraclePriceData(address(data)).get(sources[i], symbol); if (_t > now - duration){ postedPrices[_updatedSources] =_v; _updatedSources++; } } else{ (_t,_v) = getOnChain(onChainSources[i-sources.length], symbol); if (_t > now - duration){ postedPrices[_updatedSources] = _v; _updatedSources++; } } } for (uint i = 0; i <sources.length + onChainSources.length; i++){ if(i < sources.length){ (_t,_v) = OpenOraclePriceData(address(data)).get(sources[i], symbol); if (_t > now - duration){ postedPrices[_updatedSources] =_v; _updatedSources++; } } else{ (_t,_v) = getOnChain(onChainSources[i-sources.length], symbol); if (_t > now - duration){ postedPrices[_updatedSources] = _v; _updatedSources++; } } } for (uint i = 0; i <sources.length + onChainSources.length; i++){ if(i < sources.length){ (_t,_v) = OpenOraclePriceData(address(data)).get(sources[i], symbol); if (_t > now - duration){ postedPrices[_updatedSources] =_v; _updatedSources++; } } else{ (_t,_v) = getOnChain(onChainSources[i-sources.length], symbol); if (_t > now - duration){ postedPrices[_updatedSources] = _v; _updatedSources++; } } } uint64[] memory allPrices = new uint64[](_updatedSources); for (uint i=0; i < (_updatedSources); i++) { allPrices[i] = postedPrices[i]; } uint64[] memory sortedPrices = sort(allPrices); if(_updatedSources>1){ return sortedPrices[_updatedSources / 2]; } else if(_updatedSources == 1){ return sortedPrices[0]; } else{ return 0; } }
1,062,739
./full_match/10/0xf59E31f738EEF10CA94845B3Be78a0a626f2a4A5/sources/contracts/protocol/extensions/adapters/AGovernance.sol
@inheritdoc IAGovernance
function castVote(uint256 proposalId, IRigoblockGovernance.VoteType voteType) external override { IRigoblockGovernance(_getGovernance()).castVote(proposalId, voteType); }
3,782,691
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; // Interfaces import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; // Libraries import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; library LibERC721 { using Counters for Counters.Counter; using Address for address; using Strings for uint256; bytes32 internal constant ERC721_STORAGE_POSITION = keccak256("nffeels.contracts.erc721.storage"); bytes32 internal constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); bytes32 internal constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); struct Checkpoint { uint32 fromBlock; uint224 votes; } struct ERC721Storage { // Token name string name; // Token symbol string symbol; // Mapping from token ID to owner address mapping(uint256 => address) owners; // Mapping owner address to token count mapping(address => uint256) balances; // Mapping from token ID to approved address mapping(uint256 => address) tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) operatorApprovals; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) tokenURIs; // Mapping of voter delegates mapping(address => address) delegates; // Mapping of voter checkpoints mapping(address => Checkpoint[]) checkpoints; // Array of all balances at a given checkpoint Checkpoint[] totalSupplyCheckpoints; // Mapping of voting weight to token mapping(uint256 => uint256) votingWeightOfToken; // Mapping of voting weight to address mapping(address => uint256) votingWeight; // Mapping of address to nonce mapping(address => Counters.Counter) nonces; // Array of reserved token ids uint256[] reservedTokenIds; // Mapping to check if token id has been reserved mapping(uint256 => bool) isTokenIdReserved; // Wojak id counter Counters.Counter wojakIdCounter; } /** * @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 Emitted when contract owner stores `data` of `tokenId`. */ event Wojak(uint256 indexed tokenId, string data); /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); function erc721Storage() internal pure returns (ERC721Storage storage erc721s) { bytes32 position = ERC721_STORAGE_POSITION; assembly { erc721s.slot := position } } /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) internal view returns (address) { address owner = erc721Storage().owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @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 pure returns (string memory) { return ""; } /** * @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 { 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 returns (bool) { return erc721Storage().owners[tokenId] != address(0); } /** * @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, bool isUnique ) internal { safeMint(to, tokenId, isUnique, ""); } /** * @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, bool isUnique, bytes memory _data ) internal { if (isUnique) { erc721Storage().votingWeightOfToken[tokenId] = 3; } else { erc721Storage().votingWeightOfToken[tokenId] = 2; } 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 { require(to != address(0), "ERC721: mint to the zero address"); require(!exists(tokenId), "ERC721: token already minted"); require( tokenId <= maxSupply(), "ERC721Votes: total supply risks overflowing votes" ); beforeTokenTransfer(address(0), to, tokenId); erc721Storage().balances[to] += 1; erc721Storage().owners[tokenId] = to; emit Transfer(address(0), to, tokenId); afterTokenTransfer(address(0), to, tokenId); uint256 votingWeightOfToken = erc721Storage().votingWeightOfToken[ tokenId ]; erc721Storage().votingWeight[to] += votingWeightOfToken; writeCheckpoint( erc721Storage().totalSupplyCheckpoints, _add, votingWeightOfToken ); } /** * @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 { address owner = ownerOf(tokenId); beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals approve(address(0), tokenId); erc721Storage().balances[owner] -= 1; delete erc721Storage().owners[tokenId]; emit Transfer(owner, address(0), tokenId); afterTokenTransfer(owner, address(0), tokenId); if (bytes(erc721Storage().tokenURIs[tokenId]).length != 0) { delete erc721Storage().tokenURIs[tokenId]; } uint256 votingWeightOfToken = erc721Storage().votingWeightOfToken[ tokenId ]; erc721Storage().votingWeight[owner] -= votingWeightOfToken; writeCheckpoint( erc721Storage().totalSupplyCheckpoints, _subtract, votingWeightOfToken ); } /** * @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 { require( 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); erc721Storage().balances[from] -= 1; erc721Storage().balances[to] += 1; erc721Storage().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 { erc721Storage().tokenApprovals[tokenId] = to; emit Approval(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( address(msg.sender), 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; } } /* ERC721Enumerable */ /** * @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 = _balanceOf(to); erc721Storage().ownedTokens[to][length] = tokenId; erc721Storage().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 { erc721Storage().allTokensIndex[tokenId] = erc721Storage() .allTokens .length; erc721Storage().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 = _balanceOf(from) - 1; uint256 tokenIndex = erc721Storage().ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = erc721Storage().ownedTokens[from][ lastTokenIndex ]; erc721Storage().ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721Storage().ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete erc721Storage().ownedTokensIndex[tokenId]; delete erc721Storage().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 = erc721Storage().allTokens.length - 1; uint256 tokenIndex = erc721Storage().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 = erc721Storage().allTokens[lastTokenIndex]; erc721Storage().allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721Storage().allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete erc721Storage().allTokensIndex[tokenId]; erc721Storage().allTokens.pop(); } /* ERC721URIStorage */ /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require( exists(tokenId), "ERC721URIStorage: URI set of nonexistent token" ); require( bytes(_tokenURI).length > 0, "ERC721URIStorage: Invalid token URI" ); erc721Storage().tokenURIs[tokenId] = _tokenURI; } /* ERC721Votes */ /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) internal view returns (uint256) { require(blockNumber < block.number, "ERC721Votes: block not yet mined"); return checkpointsLookup( erc721Storage().checkpoints[account], blockNumber ); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) internal view returns (uint256) { require(blockNumber < block.number, "ERC721Votes: block not yet mined"); return checkpointsLookup( erc721Storage().totalSupplyCheckpoints, blockNumber ); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) internal view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function maxSupply() internal pure returns (uint224) { return type(uint224).max; } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates(delegator); uint256 delegatorVotingWeight = _getVotingWeightOf(delegator); erc721Storage().delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); moveVotingPower(currentDelegate, delegatee, delegatorVotingWeight); } function moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = writeCheckpoint( erc721Storage().checkpoints[src], _subtract, amount ); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = writeCheckpoint( erc721Storage().checkpoints[dst], _add, amount ); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push( Checkpoint({ fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight) }) ); } } /* ERC721Permit */ /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function useNonce(address owner) internal returns (uint256 current) { Counters.Counter storage nonce = erc721Storage().nonces[owner]; current = nonce.current(); nonce.increment(); } /* Hooks */ /** * @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 { 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 Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function afterTokenTransfer( address from, address to, uint256 tokenId ) internal { moveVotingPower( _delegates(from), _delegates(to), erc721Storage().votingWeightOfToken[tokenId] ); } /** * @dev Stores `data` of `tokenId` in event. * * Requirements: * * - Can only be called by contract owner. * - `tokenId` must exist. * - `data` must be specified. * * Emits a {Wojak} event. */ function setEventData(uint256 tokenId, string memory data) internal { require(exists(tokenId), "ERC721: data storage for nonexistent token"); require(bytes(data).length > 0, "ERC721: event data is not specified"); emit Wojak(tokenId, data); } /* Library helper functions */ /** * @dev Returns the number of tokens in ``owner``'s account. */ function _balanceOf(address owner) private view returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return erc721Storage().balances[owner]; } function _delegates(address account) private view returns (address) { return erc721Storage().delegates[account]; } function _getVotingWeightOf(address account) private view returns (uint256) { require( account != address(0), "ERC721Votes: voting weight query for the zero address" ); return erc721Storage().votingWeight[account]; } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } }
Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1)./
function maxSupply() internal pure returns (uint224) { return type(uint224).max; }
1,806,457
pragma solidity 0.5.11; pragma experimental ABIEncoderV2; import "./registries/ExitGameRegistryMock.sol"; import "../../src/framework/ExitGameController.sol"; import "../../src/framework/interfaces/IExitProcessor.sol"; import "../../src/vaults/Erc20Vault.sol"; import "../../src/vaults/EthVault.sol"; import "../../src/utils/TxPosLib.sol"; contract DummyExitGame is IExitProcessor { uint256 public priorityFromEnqueue; ExitGameRegistryMock public exitGameRegistry; ExitGameController public exitGameController; EthVault public ethVault; Erc20Vault public erc20Vault; event ExitFinalizedFromDummyExitGame ( uint256 indexed exitId, uint256 vaultId, address ercContract ); // override ExitProcessor interface function processExit(uint160 exitId, uint256 vaultId, address ercContract) public { emit ExitFinalizedFromDummyExitGame(exitId, vaultId, ercContract); } // setter function only for test, not a real Exit Game function function setExitGameRegistry(address _contract) public { exitGameRegistry = ExitGameRegistryMock(_contract); } function checkOnlyFromNonQuarantinedExitGame() public view returns (bool) { return exitGameRegistry.checkOnlyFromNonQuarantinedExitGame(); } // setter function only for test, not a real Exit Game function function setExitGameController(address _contract) public { exitGameController = ExitGameController(_contract); } function enqueue(uint256 _vaultId, address _token, uint64 _exitableAt, uint256 _txPos, uint160 _exitId, IExitProcessor _exitProcessor) public { priorityFromEnqueue = exitGameController.enqueue(_vaultId, _token, _exitableAt, TxPosLib.TxPos(_txPos), _exitId, _exitProcessor); } function proxyBatchFlagOutputsSpent(bytes32[] memory _outputIds) public { exitGameController.batchFlagOutputsSpent(_outputIds); } function proxyFlagOutputSpent(bytes32 _outputId) public { exitGameController.flagOutputSpent(_outputId); } // setter function only for test, not a real Exit Game function function setEthVault(EthVault _vault) public { ethVault = _vault; } function proxyEthWithdraw(address payable _target, uint256 _amount) public { ethVault.withdraw(_target, _amount); } // setter function only for test, not a real Exit Game function function setErc20Vault(Erc20Vault _vault) public { erc20Vault = _vault; } function proxyErc20Withdraw(address payable _target, address _token, uint256 _amount) public { erc20Vault.withdraw(_target, _token, _amount); } }
setter function only for test, not a real Exit Game function
function setErc20Vault(Erc20Vault _vault) public { erc20Vault = _vault; }
5,507,866
pragma solidity ^0.4.15; import "../IMoneyflow.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title SplitterBase * @dev Splitter has multiple outputs (allows to send money only to THESE addresses) */ contract SplitterBase is ISplitter, Ownable { using SafeMath for uint; bool opened = true; mapping (uint=>address) children; uint childrenCount = 0; string public name = ""; constructor(string _name) public { name = _name; } function _isOpen() internal view returns(bool){ return opened; } // ISplitter: function open() external onlyOwner{ opened = true; } function close() external onlyOwner{ opened = false; } function isOpen() external view returns(bool){ return opened; } function getChildrenCount()external view returns(uint){ return childrenCount; } function getChild(uint _index)external view returns(address){ return children[_index]; } function addChild(address _newChild) external onlyOwner { children[childrenCount] = _newChild; childrenCount = childrenCount + 1; } } /** * @title WeiTopDownSplitter * @dev Will split money from top to down (order matters!). It is possible for some children to not receive money * if they have ended. */ contract WeiTopDownSplitter is SplitterBase, IWeiReceiver { constructor(string _name) SplitterBase(_name) public { } // IWeiReceiver: // calculate only absolute outputs, but do not take into account the Percents function getMinWeiNeeded()external view returns(uint){ if(!_isOpen()){ return 0; } uint total = 0; for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getMinWeiNeeded(); total = total + needed; } return total; } function getTotalWeiNeeded(uint _inputWei)external view returns(uint){ return _getTotalWeiNeeded(_inputWei); } function _getTotalWeiNeeded(uint _inputWei)internal view returns(uint){ if(!_isOpen()){ return 0; } uint total = 0; for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(_inputWei); total = total + needed; // this should be reduced because next child can get only '_inputWei minus what prev. child got' if(_inputWei>needed){ _inputWei-=needed; }else{ _inputWei = 0; } } return total; } function getPercentsMul100()external view returns(uint){ uint total = 0; for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); total = total + c.getPercentsMul100(); } // truncate, no more than 100% allowed! if(total>10000){ return 10000; } return total; } function isNeedsMoney()constant public returns(bool){ if(!_isOpen()){ return false; } for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); // if at least 1 child needs money -> return true if(c.isNeedsMoney()){ return true; } } return false; } // WeiSplitter allows to receive money from ANY address // WeiSplitter should not hold any funds. Instead - it should split immediately // If WeiSplitter receives less or more money than needed -> exception // // TODO: this can be optimized, no need to traverse other hierarchy step // we can get the 'terminal' items and send money DIRECTLY FROM the signle source // this will save gas // See this - https://github.com/Thetta/SmartContracts/issues/40 function processFunds(uint _currentFlow) external payable{ require(_isOpen()); uint amount = _currentFlow; // TODO: can remove this line? // transfer below will throw if not enough money? require(amount>=_getTotalWeiNeeded(_currentFlow)); // ??? //require(amount>=getMinWeiNeeded()); // DO NOT SEND LESS! // DO NOT SEND MORE! for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(amount); // send money. can throw! // we sent needed money but specifying TOTAL amount of flow // this help relative Splitters to calculate how to split money c.processFunds.value(needed)(amount); // this should be reduced because next child can get only 'amount minus what prev. child got' if(amount>=needed){ amount = amount - needed; }else{ amount = 0; } } } function() public { } } /** * @title WeiUnsortedSplitter * @dev Will split money (order does not matter!). */ contract WeiUnsortedSplitter is SplitterBase, IWeiReceiver { constructor(string _name) SplitterBase(_name) public { } // IWeiReceiver: // calculate only absolute outputs, but do not take into account the Percents function getMinWeiNeeded()external view returns(uint){ if(!_isOpen()){ return 0; } uint total = 0; for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getMinWeiNeeded(); total = total + needed; } return total; } function getTotalWeiNeeded(uint _inputWei)external view returns(uint){ return _getTotalWeiNeeded(_inputWei); } function _getTotalWeiNeeded(uint _inputWei)internal view returns(uint){ if(!_isOpen()){ return 0; } uint total = 0; for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(_inputWei); total = total + needed; } return total; } function getPercentsMul100()external view returns(uint){ uint total = 0; for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); total = total + c.getPercentsMul100(); } // truncate, no more than 100% allowed! if(total>10000){ return 10000; } return total; } function isNeedsMoney()external view returns(bool){ if(!_isOpen()){ return false; } for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); // if at least 1 child needs money -> return true if(c.isNeedsMoney()){ return true; } } return false; } // WeiSplitter allows to receive money from ANY address // WeiSplitter should not hold any funds. Instead - it should split immediately // If WeiSplitter receives less or more money than needed -> exception function processFunds(uint _currentFlow) external payable{ require(_isOpen()); uint amount = msg.value; // TODO: can remove this line? // transfer below will throw if not enough money? require(amount>=_getTotalWeiNeeded(_currentFlow)); // DO NOT SEND LESS! // DO NOT SEND MORE! for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(_currentFlow); // send money. can throw! // we sent needed money but specifying TOTAL amount of flow // this help relative Splitters to calculate how to split money c.processFunds.value(needed)(_currentFlow); } } function() public { } }
WeiSplitter allows to receive money from ANY address WeiSplitter should not hold any funds. Instead - it should split immediately If WeiSplitter receives less or more money than needed -> exception TODO: can remove this line? transfer below will throw if not enough money? DO NOT SEND LESS! DO NOT SEND MORE! send money. can throw! we sent needed money but specifying TOTAL amount of flow this help relative Splitters to calculate how to split money
function processFunds(uint _currentFlow) external payable{ require(_isOpen()); uint amount = msg.value; require(amount>=_getTotalWeiNeeded(_currentFlow)); for(uint i=0; i<childrenCount; ++i){ IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(_currentFlow); c.processFunds.value(needed)(_currentFlow); } }
5,422,586
pragma solidity ^0.4.4; import 'token/TokenEmission.sol'; import 'common/Object.sol'; /** @dev Ambix contract is used for morph Token set to another Token's by rule (recipe). In distillation process given Token's are burned and result generated by emission. The recipe presented as equation in form: (N1 * A1 | N'1 * A'1 | N''1 * A''1 ...) & (N2 * A2 | N'2 * A'2 | N''2 * A''2 ...) ... & (Nn * An | N'n * A'n | N''n * A''n ...) = M1 * B1 & M2 * B2 ... & Mm * Bm where A, B - input and output tokens N, M - token value coeficients n, m - input / output dimetion size | - is alternative operator (logical OR) & - is associative operator (logical AND) This says that `Ambix` should receive (approve) left part of equation and send (transfer) right part. */ contract Ambix is Object { /* Recipe fields */ TokenEmission[][] public rSource; uint[][] public rSourceCoef; TokenEmission[] public rSink; uint[] public rSinkCoef; /* Recipe end */ /** * @dev Set source by index * @param _index is a source index * @param _source is a list of source alternatives * @param _coef is a list of source alternatives coeficients */ function setSource(uint _index, TokenEmission[] _source, uint[] _coef) onlyOwner { if (_source.length != _coef.length) throw; // Lenght fix if (rSource.length < _index + 1) { rSource.length = _index + 1; rSourceCoef.length = _index + 1; } // Push values delete rSource[_index]; delete rSourceCoef[_index]; for (uint i = 0; i < _source.length; ++i) { rSource[_index].push(_source[i]); rSourceCoef[_index].push(_coef[i]); } } /** * @dev Set sink * @param _sink is a list of sink tokens * @param _coef is a list of sink coeficients */ function setSink(TokenEmission[] _sink, uint[] _coef) onlyOwner { if (_sink.length != _coef.length) throw; delete rSink; delete rSource; for (uint i = 0; i < _sink.length; ++i) { rSink.push(_sink[i]); rSinkCoef.push(_coef[i]); } } /** * @dev Run distillation process * @notice Input tokens(any one of alternative) should be approved to this */ function run() { TokenEmission token; uint value; uint i; uint j; // Take a source tokens for (i = 0; i < rSource.length; ++i) { bool tokenBurned = false; // Try to transfer alternatives and burn it for (j = 0; j < rSource[i].length; ++j) { token = rSource[i][j]; value = rSourceCoef[i][j]; if (token.transferFrom(msg.sender, this, value)) { token.burn(value); tokenBurned = true; break; } } if (!tokenBurned) throw; } // Generate sink tokens for (i = 0; i < rSink.length; ++i) { token = rSink[i]; value = rSinkCoef[i]; token.emission(value); if (!token.transfer(msg.sender, value)) throw; } } }
Set sink _sink is a list of sink tokens _coef is a list of sink coeficients/
function setSink(TokenEmission[] _sink, uint[] _coef) onlyOwner { if (_sink.length != _coef.length) throw; delete rSink; delete rSource; for (uint i = 0; i < _sink.length; ++i) { rSink.push(_sink[i]); rSinkCoef.push(_coef[i]); } }
1,778,515
pragma solidity ^0.5.2; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { ERC721Full } from "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { BytesLib } from "../common/lib/BytesLib.sol"; import { ECVerify } from "../common/lib/ECVerify.sol"; import { Merkle } from "../common/lib/Merkle.sol"; import { Lockable } from "../common/mixin/Lockable.sol"; import { RootChainable } from "../common/mixin/RootChainable.sol"; import { Registry } from "../common/Registry.sol"; import { IStakeManager } from "./IStakeManager.sol"; import { Validator } from "./Validator.sol"; import { ValidatorContract } from "./Validator.sol"; contract StakeManager is Validator, IStakeManager, RootChainable, Lockable { using SafeMath for uint256; using ECVerify for bytes32; using Merkle for bytes32; IERC20 public token; address public registry; // genesis/governance variables uint256 public dynasty = 2**13; // unit: epoch 50 days uint256 public checkpointReward = 10000 * (10**18); // @todo update according to Chain uint256 public MIN_DEPOSIT_SIZE = (10**18); // in ERC20 token uint256 public EPOCH_LENGTH = 256; // unit : block uint256 public UNSTAKE_DELAY = dynasty.mul(2); // unit: epoch uint256 public checkPointBlockInterval = 255; // TODO: add events and gov. based update function uint256 public proposerToSignerRewards = 10; // will be used with fraud proof uint256 public validatorThreshold = 10; //128 uint256 public minLockInPeriod = 2; // unit: dynasty uint256 public totalStaked; uint256 public currentEpoch = 1; uint256 public NFTCounter = 1; uint256 public totalRewards; uint256 public totalRewardsLiquidated; uint256 public auctionPeriod = dynasty.div(4); // 1 week in epochs bytes32 public accountStateRoot; // on dynasty update certain amount of cooldown period where there is no validator auction uint256 replacementCoolDown; enum Status { Inactive, Active, Locked } struct Validator { uint256 amount; uint256 reward; uint256 claimedRewards; uint256 activationEpoch; uint256 deactivationEpoch; uint256 jailTime; address signer; address contractAddress; Status status; } struct Auction { uint256 amount; uint256 startEpoch; address user; } struct State { int256 amount; int256 stakerCount; } // signer to Validator mapping mapping (address => uint256) public signerToValidator; // validator metadata mapping (uint256 => Validator) public validators; //Mapping for epoch to totalStake for that epoch mapping (uint256 => State) public validatorState; //Ongoing auctions for validatorId mapping (uint256 => Auction) public validatorAuction; constructor (address _registry, address _rootchain) ERC721Full("Matic Validator", "MV") public { registry = _registry; rootChain = _rootchain; } modifier onlyStaker(uint256 validatorId) { require(ownerOf(validatorId) == msg.sender); _; } modifier onlySlashingMananger() { require(Registry(registry).getSlashingManagerAddress() == msg.sender); _; } function stake(uint256 amount, address signer, bool isContract) external { stakeFor(msg.sender, amount, signer, isContract); } function stakeFor(address user, uint256 amount, address signer, bool isContract) public onlyWhenUnlocked { require(currentValidatorSetSize() < validatorThreshold); require(balanceOf(user) == 0, "Only one time staking is allowed"); require(amount > MIN_DEPOSIT_SIZE); require(signerToValidator[signer] == 0); require(token.transferFrom(msg.sender, address(this), amount), "Transfer stake failed"); _stakeFor(user, amount, signer, isContract); } function _stakeFor(address user, uint256 amount, address signer, bool isContract) internal { totalStaked = totalStaked.add(amount); validators[NFTCounter] = Validator({ reward: 0, amount: amount, claimedRewards: 0, activationEpoch: currentEpoch, deactivationEpoch: 0, jailTime: 0, signer: signer, contractAddress: isContract ? address(new ValidatorContract(user, registry)) : address(0x0), status : Status.Active }); _mint(user, NFTCounter); signerToValidator[signer] = NFTCounter; updateTimeLine(currentEpoch, int256(amount), 1); // no Auctions for 1 dynasty validatorAuction[NFTCounter].startEpoch = currentEpoch.add(dynasty); emit Staked(signer, NFTCounter, currentEpoch, amount, totalStaked); NFTCounter = NFTCounter.add(1); } function perceivedStakeFactor(uint256 validatorId) internal returns(uint256){ // TODO: use age, rewardRatio, and slashing/reward rate return 1; } function startAuction(uint256 validatorId, uint256 amount) external { require(isValidator(validatorId)); // when dynasty period is updated validators are in cool down period require(replacementCoolDown == 0 || replacementCoolDown <= currentEpoch, "Cool down period"); require(auctionPeriod >= currentEpoch.sub(validatorAuction[validatorId].startEpoch), "Invalid auction period"); // (dynasty--auctionPeriod)--(dynasty--auctionPeriod)--(dynasty--auctionPeriod) // if it's auctionPeriod then will get residue from (CurrentPeriod of validator )%(dynasty--auctionPeriod) // make sure that its `auctionPeriod` window // dynasty = 30, auctionPeriod = 7, activationEpoch = 1, currentEpoch = 39 // residue 1 = (39-1)% (30+7), if residue-dynasty > 0 it's `auctionPeriod` require((currentEpoch.sub(validators[validatorId].activationEpoch) % dynasty.add(auctionPeriod)) > dynasty, "Not an auction time"); require(token.transferFrom(msg.sender, address(this), amount), "Transfer amount failed"); uint256 perceivedStake = validators[validatorId].amount.mul(perceivedStakeFactor(validatorId)); perceivedStake = Math.max(perceivedStake, validatorAuction[validatorId].amount); require(perceivedStake < amount, "Must bid higher amount"); // create new auction if (validatorAuction[validatorId].amount == 0) { validatorAuction[validatorId] = Auction({ amount: amount, startEpoch: currentEpoch, user: msg.sender }); } else { //replace prev auction Auction storage auction = validatorAuction[validatorId]; require(token.transfer(auction.user, auction.amount)); auction.amount = amount; auction.user = msg.sender; } emit StartAuction(validatorId, validators[validatorId].amount, validatorAuction[validatorId].amount); } function confirmAuctionBid(uint256 validatorId, address signer, bool isContract) external onlyWhenUnlocked { Auction storage auction = validatorAuction[validatorId]; Validator storage validator = validators[validatorId]; require(auction.user == msg.sender); require(auctionPeriod.add(auction.startEpoch) <= currentEpoch, "Confirmation is not allowed before auctionPeriod"); // validator is last auctioner if (auction.user == ownerOf(validatorId)) { uint256 refund = validator.amount; require(token.transfer(auction.user, refund)); validator.amount = auction.amount; //cleanup auction data auction.amount = 0; auction.user = address(0x0); auction.startEpoch = currentEpoch.add(dynasty); //update total stake amount totalStaked = totalStaked.add(validator.amount.sub(refund)); emit StakeUpdate(validatorId, refund, validator.amount); emit ConfirmAuction(validatorId, validatorId, validator.amount); } else { // dethrone _unstake(validatorId, currentEpoch); _stakeFor(auction.user, auction.amount, signer, isContract); emit ConfirmAuction(NFTCounter.sub(1), validatorId, auction.amount); delete validatorAuction[validatorId]; } } function unstake(uint256 validatorId) external onlyStaker(validatorId) { require(validatorAuction[validatorId].amount == 0, "Wait for auction completion"); uint256 exitEpoch = currentEpoch.add(1);// notice period require(validators[validatorId].activationEpoch > 0 && validators[validatorId].deactivationEpoch == 0 && validators[validatorId].status == Status.Active); _unstake(validatorId, exitEpoch); } function _unstake(uint256 validatorId, uint256 exitEpoch) internal { //Todo: add state here consider jail uint256 amount = validators[validatorId].amount; validators[validatorId].deactivationEpoch = exitEpoch; // unbond all delegators in future int256 delegationAmount = 0; if (validators[validatorId].contractAddress != address(0x0)) { delegationAmount = ValidatorContract(validators[validatorId].contractAddress).unBondAllLazy(exitEpoch); } // update future updateTimeLine(exitEpoch, -(int256(amount) + delegationAmount ), -1); emit UnstakeInit(msg.sender, validatorId, exitEpoch, amount); } function unstakeClaim(uint256 validatorId) public onlyStaker(validatorId) { // can only claim stake back after WITHDRAWAL_DELAY require(validators[validatorId].deactivationEpoch > 0 && validators[validatorId].deactivationEpoch.add(WITHDRAWAL_DELAY) <= currentEpoch); uint256 amount = validators[validatorId].amount; totalStaked = totalStaked.sub(amount); // TODO :add slashing here use soft slashing in slash amt variable _burn(validatorId); delete signerToValidator[validators[validatorId].signer]; // delete validators[validatorId]; require(token.transfer(msg.sender, amount + validators[validatorId].reward)); emit Unstaked(msg.sender, validatorId, amount, totalStaked); } // slashing and jail interface function restake(uint256 validatorId, uint256 amount, bool stakeRewards) public onlyStaker(validatorId) { require(validators[validatorId].deactivationEpoch < currentEpoch, "No use of restaking"); if (amount > 0) { require(token.transferFrom(msg.sender, address(this), amount), "Transfer stake"); } if (stakeRewards) { amount += validators[validatorId].reward; validators[validatorId].reward = 0; } totalStaked = totalStaked.add(amount); validators[validatorId].amount += amount; validatorState[currentEpoch].amount = ( validatorState[currentEpoch].amount + int256(amount)); emit StakeUpdate(validatorId, validators[validatorId].amount.sub(amount), validators[validatorId].amount); emit ReStaked(validatorId, validators[validatorId].amount, totalStaked); } function claimRewards(uint256 validatorId, uint256 accountBalance, uint256 index, bytes memory proof) public /*onlyStaker(validatorId) */ { // accountState = keccak256(abi.encodePacked(validatorId, accountBalance)) require(keccak256(abi.encodePacked(validatorId, accountBalance)).checkMembership(index, accountStateRoot, proof)); uint256 _reward = accountBalance.sub(validators[validatorId].claimedRewards); address _contract = validators[validatorId].contractAddress; if (_contract == address(0x0)) { validators[validatorId].reward = validators[validatorId].reward.add(_reward); } else { // TODO: delegator bond/share rate if return needs to be updated periodically // otherwise validator can delay and get all the delegators reward ValidatorContract(_contract).updateRewards(_reward, currentEpoch, validators[validatorId].amount); } totalRewardsLiquidated += _reward; require(totalRewardsLiquidated <= totalRewards, "Liquidating more rewards then checkpoints submitted");// pos 2/3+1 is colluded validators[validatorId].claimedRewards = accountBalance; emit ClaimRewards(validatorId, _reward, accountBalance); } function withdrawRewards(uint256 validatorId) public onlyStaker(validatorId) { uint256 amount = validators[validatorId].reward; address _contract = validators[validatorId].contractAddress; if (_contract != address(0x0)) { amount = amount.add(ValidatorContract(_contract).withdrawRewardsValidator()); } validators[validatorId].reward = 0; require(token.transfer(msg.sender, amount), "Insufficent rewards"); } function delegationTransfer(uint256 amount, address delegator) external { require(Registry(registry).getDelegationManagerAddress() == msg.sender); require(token.transfer(delegator, amount), "Insufficent rewards"); } // if not jailed then in state of warning, else will be unstaking after x epoch function slash(uint256 validatorId, uint256 slashingRate, uint256 jailCheckpoints) public onlySlashingMananger { // if contract call contract.slash if (validators[validatorId].contractAddress != address(0x0)) { ValidatorContract(validators[validatorId].contractAddress).slash(slashingRate, currentEpoch, currentEpoch); } uint256 amount = validators[validatorId].amount.mul(slashingRate).div(100); validators[validatorId].amount = validators[validatorId].amount.sub(amount); if(validators[validatorId].amount < MIN_DEPOSIT_SIZE || jailCheckpoints > 0) { jail(validatorId, jailCheckpoints); } // todo: slash event emit StakeUpdate(validatorId, validators[validatorId].amount.add(amount), validators[validatorId].amount); } function unJail(uint256 validatorId) public onlyStaker(validatorId) { require(validators[validatorId].deactivationEpoch > currentEpoch && validators[validatorId].jailTime <= currentEpoch && validators[validatorId].status == Status.Locked); uint256 amount = validators[validatorId].amount; require(amount >= MIN_DEPOSIT_SIZE); uint256 exitEpoch = validators[validatorId].deactivationEpoch; int256 delegationAmount = 0; if (validators[validatorId].contractAddress != address(0x0)) { delegationAmount = ValidatorContract(validators[validatorId].contractAddress).revertLazyUnBonding(exitEpoch); } // undo timline so that validator is normal validator updateTimeLine(exitEpoch, (int256(amount) + delegationAmount ), 1); validators[validatorId].deactivationEpoch = 0; validators[validatorId].status = Status.Active; validators[validatorId].jailTime = 0; } // in context of slashing function jail(uint256 validatorId, uint256 jailCheckpoints) public /** only*/ { // Todo: requires and more conditions uint256 amount = validators[validatorId].amount; // should unbond instantly uint256 exitEpoch = currentEpoch.add(UNSTAKE_DELAY); // jail period int256 delegationAmount = 0; validators[validatorId].jailTime = jailCheckpoints; if (validators[validatorId].contractAddress != address(0x0)) { delegationAmount = ValidatorContract(validators[validatorId].contractAddress).unBondAllLazy(exitEpoch); } // update future in case of no `unJail` updateTimeLine(exitEpoch, -(int256(amount) + delegationAmount ), -1); validators[validatorId].deactivationEpoch = exitEpoch; validators[validatorId].status = Status.Locked; emit Jailed(validatorId, exitEpoch); } function updateTimeLine(uint256 epoch, int256 amount, int256 stakerCount) private { validatorState[epoch].amount += amount; validatorState[epoch].stakerCount += stakerCount; } // returns valid validator for current epoch function getCurrentValidatorSet() public view returns (uint256[] memory) { uint256[] memory _validators = new uint256[](validatorThreshold); uint256 validator; uint256 k = 0; for (uint96 i = 0;i < totalSupply() ;i++) { validator = tokenByIndex(i); if (isValidator(validator)) { _validators[k++] = validator; } } return _validators; } function getStakerDetails(uint256 validatorId) public view returns(uint256, uint256, uint256, address, uint256) { return ( validators[validatorId].amount, validators[validatorId].activationEpoch, validators[validatorId].deactivationEpoch, validators[validatorId].signer, uint256(validators[validatorId].status) ); } function getValidatorId(address user) public view returns(uint256) { return tokenOfOwnerByIndex(user, 0); } function totalStakedFor(address user) external view returns (uint256) { if (user == address(0x0) || balanceOf(user) == 0) { return 0; } return validators[tokenOfOwnerByIndex(user, 0)].amount; } function supportsHistory() external pure returns (bool) { return false; } // set staking Token function setToken(address _token) public onlyOwner { require(_token != address(0x0)); token = IERC20(_token); } // Change the number of validators required to allow a passed header root function updateValidatorThreshold(uint256 newThreshold) public onlyOwner { require(newThreshold > 0); emit ThresholdChange(newThreshold, validatorThreshold); validatorThreshold = newThreshold; } function updateCheckPointBlockInterval(uint256 _blocks) public onlyOwner { require(_blocks > 0, "Blocks interval must be non-zero"); checkPointBlockInterval = _blocks; } // Change reward for each checkpoint function updateCheckpointReward(uint256 newReward) public onlyOwner { require(newReward > 0); emit RewardUpdate(newReward, checkpointReward); checkpointReward = newReward; } function updateValidatorState(uint256 validatorId, uint256 epoch, int256 amount) public { require(Registry(registry).getDelegationManagerAddress() == msg.sender); require(epoch >= currentEpoch, "Can't change past"); validatorState[epoch].amount = ( validatorState[epoch].amount + amount ); } function updateDynastyValue(uint256 newDynasty) public onlyOwner { require(newDynasty > 0); emit DynastyValueChange(newDynasty, dynasty); dynasty = newDynasty; UNSTAKE_DELAY = dynasty.div(2); WITHDRAWAL_DELAY = dynasty.mul(2); auctionPeriod = dynasty.div(4); // set cool down period replacementCoolDown = currentEpoch.add(auctionPeriod); } function updateSigner(uint256 validatorId, address _signer) public onlyStaker(validatorId) { require(_signer != address(0x0) && signerToValidator[_signer] == 0); // update signer event emit SignerChange(validatorId, validators[validatorId].signer, _signer); delete signerToValidator[validators[validatorId].signer]; signerToValidator[_signer] = validatorId; validators[validatorId].signer = _signer; } function finalizeCommit() internal { uint256 nextEpoch = currentEpoch.add(1); // update totalstake and validator count validatorState[nextEpoch].amount = ( validatorState[currentEpoch].amount + validatorState[nextEpoch].amount ); validatorState[nextEpoch].stakerCount = ( validatorState[currentEpoch].stakerCount + validatorState[nextEpoch].stakerCount ); // erase old data/history delete validatorState[currentEpoch]; currentEpoch = nextEpoch; } function updateMinLockInPeriod(uint256 epochs) public onlyOwner { minLockInPeriod = epochs; } function currentValidatorSetSize() public view returns (uint256) { return uint256(validatorState[currentEpoch].stakerCount); } function currentValidatorSetTotalStake() public view returns (uint256) { return uint256(validatorState[currentEpoch].amount); } function getValidatorContract(uint256 validatorId) public view returns(address) { return validators[validatorId].contractAddress; } function isValidator(uint256 validatorId) public view returns (bool) { return ( validators[validatorId].amount > 0 && (validators[validatorId].activationEpoch != 0 && validators[validatorId].activationEpoch <= currentEpoch ) && (validators[validatorId].deactivationEpoch == 0 || validators[validatorId].deactivationEpoch > currentEpoch) && validators[validatorId].status == Status.Active // Todo: reduce logic ); } function checkSignatures(uint256 blockInterval, bytes32 voteHash, bytes32 stateRoot, bytes memory sigs) public onlyRootChain returns(uint256) { uint256 stakePower; uint256 _totalStake; (stakePower, _totalStake) = checkTwoByThreeMajority(voteHash, sigs); // checkpoint rewards are based on BlockInterval multiplied on `checkpointReward` // with actual `blockInterval` // eg. checkpointReward = 10 Tokens, checkPointBlockInterval = 250, blockInterval = 500 then reward // for this checkpoint is 20 Tokens uint256 _reward = blockInterval.mul(checkpointReward).div(checkPointBlockInterval); _reward = Math.min(checkpointReward, _reward).mul(stakePower).div(_totalStake); totalRewards = totalRewards.add(_reward); // update stateMerkleTree root for accounts balance on heimdall chain // for previous checkpoint rewards accountStateRoot = stateRoot; finalizeCommit(); return _reward; } function checkTwoByThreeMajority(bytes32 voteHash, bytes memory sigs) public view returns(uint256, uint256) { // total voting power uint256 stakePower; uint256 validatorId; address lastAdd = address(0x0); // cannot have address(0x0) as an owner for (uint64 i = 0; i < sigs.length; i += 65) { bytes memory sigElement = BytesLib.slice(sigs, i, 65); address signer = voteHash.ecrecovery(sigElement); validatorId = signerToValidator[signer]; // check if signer is stacker and not proposer if (signer == lastAdd) { break; } else if ( isValidator(validatorId) && signer > lastAdd ) { lastAdd = signer; address _contract = validators[validatorId].contractAddress; stakePower = stakePower.add(validators[validatorId].amount); // add delegation power if (_contract != address(0x0)) { stakePower = stakePower.add(ValidatorContract(_contract).delegatedAmount()); } } } uint256 _totalStake = currentValidatorSetTotalStake(); require(stakePower >= _totalStake.mul(2).div(3).add(1)); return (stakePower, _totalStake); } function challangeStateRootUpdate(bytes memory checkpointTx /* txData from submitCheckpoint */) public { // TODO: check for 2/3+1 sig and validate non-inclusion in newStateUpdate } }
when dynasty period is updated validators are in cool down period (dynasty--auctionPeriod)--(dynasty--auctionPeriod)--(dynasty--auctionPeriod) if it's auctionPeriod then will get residue from (CurrentPeriod of validator )%(dynasty--auctionPeriod) make sure that its `auctionPeriod` window dynasty = 30, auctionPeriod = 7, activationEpoch = 1, currentEpoch = 39 residue 1 = (39-1)% (30+7), if residue-dynasty > 0 it's `auctionPeriod` create new auction
function startAuction(uint256 validatorId, uint256 amount) external { require(isValidator(validatorId)); require(replacementCoolDown == 0 || replacementCoolDown <= currentEpoch, "Cool down period"); require(auctionPeriod >= currentEpoch.sub(validatorAuction[validatorId].startEpoch), "Invalid auction period"); require((currentEpoch.sub(validators[validatorId].activationEpoch) % dynasty.add(auctionPeriod)) > dynasty, "Not an auction time"); require(token.transferFrom(msg.sender, address(this), amount), "Transfer amount failed"); uint256 perceivedStake = validators[validatorId].amount.mul(perceivedStakeFactor(validatorId)); perceivedStake = Math.max(perceivedStake, validatorAuction[validatorId].amount); require(perceivedStake < amount, "Must bid higher amount"); if (validatorAuction[validatorId].amount == 0) { validatorAuction[validatorId] = Auction({ amount: amount, startEpoch: currentEpoch, user: msg.sender }); Auction storage auction = validatorAuction[validatorId]; require(token.transfer(auction.user, auction.amount)); auction.amount = amount; auction.user = msg.sender; } emit StartAuction(validatorId, validators[validatorId].amount, validatorAuction[validatorId].amount); }
2,484,371
pragma solidity ^0.5.16; import "../AddressResolver.sol"; import "../BaseMigration.sol"; import "../DebtCache.sol"; import "../ExchangeRatesWithDexPricing.sol"; import "../ExchangeState.sol"; import "../FeePool.sol"; import "../FeePoolEternalStorage.sol"; import "../Issuer.sol"; import "../MultiCollateralSynth.sol"; import "../Proxy.sol"; import "../ProxyERC20.sol"; import "../RewardEscrow.sol"; import "../SystemStatus.sol"; import "../TokenState.sol"; interface ISynthetixNamedContract { // solhint-disable func-name-mixedcase function CONTRACT_NAME() external view returns (bytes32); } // solhint-disable contract-name-camelcase library MigrationLib_Diphda { // ---------------------------- // EXISTING SYNTHETIX CONTRACTS // ---------------------------- // https://etherscan.io/address/0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83 AddressResolver public constant addressresolver_i = AddressResolver(0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83); // https://etherscan.io/address/0xb440DD674e1243644791a4AdfE3A2AbB0A92d309 Proxy public constant proxyfeepool_i = Proxy(0xb440DD674e1243644791a4AdfE3A2AbB0A92d309); // https://etherscan.io/address/0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB FeePoolEternalStorage public constant feepooleternalstorage_i = FeePoolEternalStorage(0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB); // https://etherscan.io/address/0x545973f28950f50fc6c7F52AAb4Ad214A27C0564 ExchangeState public constant exchangestate_i = ExchangeState(0x545973f28950f50fc6c7F52AAb4Ad214A27C0564); // https://etherscan.io/address/0x696c905F8F8c006cA46e9808fE7e00049507798F SystemStatus public constant systemstatus_i = SystemStatus(0x696c905F8F8c006cA46e9808fE7e00049507798F); // https://etherscan.io/address/0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F RewardEscrow public constant rewardescrow_i = RewardEscrow(0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F); // https://etherscan.io/address/0x3B2f389AeE480238A49E3A9985cd6815370712eB FeePool public constant feepool_i = FeePool(0x3B2f389AeE480238A49E3A9985cd6815370712eB); // https://etherscan.io/address/0x1620Aa736939597891C1940CF0d28b82566F9390 DebtCache public constant debtcache_i = DebtCache(0x1620Aa736939597891C1940CF0d28b82566F9390); // https://etherscan.io/address/0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9 ExchangeRatesWithDexPricing public constant exchangerates_i = ExchangeRatesWithDexPricing(0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9); // https://etherscan.io/address/0x7df9b3f8f1C011D8BD707430e97E747479DD532a MultiCollateralSynth public constant synthsusd_i = MultiCollateralSynth(0x7df9b3f8f1C011D8BD707430e97E747479DD532a); // https://etherscan.io/address/0x05a9CBe762B36632b3594DA4F082340E0e5343e8 TokenState public constant tokenstatesusd_i = TokenState(0x05a9CBe762B36632b3594DA4F082340E0e5343e8); // https://etherscan.io/address/0x57Ab1ec28D129707052df4dF418D58a2D46d5f51 Proxy public constant proxysusd_i = Proxy(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); // https://etherscan.io/address/0x1b06a00Df0B27E7871E753720D4917a7D1aac68b MultiCollateralSynth public constant synthseur_i = MultiCollateralSynth(0x1b06a00Df0B27E7871E753720D4917a7D1aac68b); // https://etherscan.io/address/0x6568D9e750fC44AF00f857885Dfb8281c00529c4 TokenState public constant tokenstateseur_i = TokenState(0x6568D9e750fC44AF00f857885Dfb8281c00529c4); // https://etherscan.io/address/0xD71eCFF9342A5Ced620049e616c5035F1dB98620 ProxyERC20 public constant proxyseur_i = ProxyERC20(0xD71eCFF9342A5Ced620049e616c5035F1dB98620); // https://etherscan.io/address/0xB82f11f3168Ece7D56fe6a5679567948090de7C5 MultiCollateralSynth public constant synthsjpy_i = MultiCollateralSynth(0xB82f11f3168Ece7D56fe6a5679567948090de7C5); // https://etherscan.io/address/0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed TokenState public constant tokenstatesjpy_i = TokenState(0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed); // https://etherscan.io/address/0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d ProxyERC20 public constant proxysjpy_i = ProxyERC20(0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d); // https://etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C MultiCollateralSynth public constant synthsaud_i = MultiCollateralSynth(0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C); // https://etherscan.io/address/0xCb29D2cf2C65d3Be1d00F07f3441390432D55203 TokenState public constant tokenstatesaud_i = TokenState(0xCb29D2cf2C65d3Be1d00F07f3441390432D55203); // https://etherscan.io/address/0xF48e200EAF9906362BB1442fca31e0835773b8B4 ProxyERC20 public constant proxysaud_i = ProxyERC20(0xF48e200EAF9906362BB1442fca31e0835773b8B4); // https://etherscan.io/address/0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf MultiCollateralSynth public constant synthsgbp_i = MultiCollateralSynth(0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf); // https://etherscan.io/address/0x7e88D19A79b291cfE5696d496055f7e57F537A75 TokenState public constant tokenstatesgbp_i = TokenState(0x7e88D19A79b291cfE5696d496055f7e57F537A75); // https://etherscan.io/address/0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F ProxyERC20 public constant proxysgbp_i = ProxyERC20(0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F); // https://etherscan.io/address/0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d MultiCollateralSynth public constant synthschf_i = MultiCollateralSynth(0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d); // https://etherscan.io/address/0x52496fE8a4feaEFe14d9433E00D48E6929c13deC TokenState public constant tokenstateschf_i = TokenState(0x52496fE8a4feaEFe14d9433E00D48E6929c13deC); // https://etherscan.io/address/0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d ProxyERC20 public constant proxyschf_i = ProxyERC20(0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d); // https://etherscan.io/address/0x527637bE27640d6C3e751d24DC67129A6d13E11C MultiCollateralSynth public constant synthskrw_i = MultiCollateralSynth(0x527637bE27640d6C3e751d24DC67129A6d13E11C); // https://etherscan.io/address/0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730 TokenState public constant tokenstateskrw_i = TokenState(0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730); // https://etherscan.io/address/0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B ProxyERC20 public constant proxyskrw_i = ProxyERC20(0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B); // https://etherscan.io/address/0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6 MultiCollateralSynth public constant synthsbtc_i = MultiCollateralSynth(0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6); // https://etherscan.io/address/0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67 TokenState public constant tokenstatesbtc_i = TokenState(0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67); // https://etherscan.io/address/0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6 ProxyERC20 public constant proxysbtc_i = ProxyERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6); // https://etherscan.io/address/0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6 MultiCollateralSynth public constant synthseth_i = MultiCollateralSynth(0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6); // https://etherscan.io/address/0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c TokenState public constant tokenstateseth_i = TokenState(0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c); // https://etherscan.io/address/0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb ProxyERC20 public constant proxyseth_i = ProxyERC20(0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb); // https://etherscan.io/address/0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6 MultiCollateralSynth public constant synthslink_i = MultiCollateralSynth(0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6); // https://etherscan.io/address/0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0 TokenState public constant tokenstateslink_i = TokenState(0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0); // https://etherscan.io/address/0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6 ProxyERC20 public constant proxyslink_i = ProxyERC20(0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6); // https://etherscan.io/address/0xB34F4d7c207D8979D05EDb0F63f174764Bd67825 MultiCollateralSynth public constant synthsada_i = MultiCollateralSynth(0xB34F4d7c207D8979D05EDb0F63f174764Bd67825); // https://etherscan.io/address/0x9956c5019a24fbd5B506AD070b771577bAc5c343 TokenState public constant tokenstatesada_i = TokenState(0x9956c5019a24fbd5B506AD070b771577bAc5c343); // https://etherscan.io/address/0xe36E2D3c7c34281FA3bC737950a68571736880A1 ProxyERC20 public constant proxysada_i = ProxyERC20(0xe36E2D3c7c34281FA3bC737950a68571736880A1); // https://etherscan.io/address/0x95aE43E5E96314E4afffcf19D9419111cd11169e MultiCollateralSynth public constant synthsaave_i = MultiCollateralSynth(0x95aE43E5E96314E4afffcf19D9419111cd11169e); // https://etherscan.io/address/0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0 TokenState public constant tokenstatesaave_i = TokenState(0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0); // https://etherscan.io/address/0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076 ProxyERC20 public constant proxysaave_i = ProxyERC20(0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076); // https://etherscan.io/address/0x27b45A4208b87A899009f45888139882477Acea5 MultiCollateralSynth public constant synthsdot_i = MultiCollateralSynth(0x27b45A4208b87A899009f45888139882477Acea5); // https://etherscan.io/address/0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077 TokenState public constant tokenstatesdot_i = TokenState(0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077); // https://etherscan.io/address/0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6 ProxyERC20 public constant proxysdot_i = ProxyERC20(0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6); // https://etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662 MultiCollateralSynth public constant synthsethbtc_i = MultiCollateralSynth(0x6DF798ec713b33BE823b917F27820f2aA0cf7662); // https://etherscan.io/address/0x042A7A0022A7695454ac5Be77a4860e50c9683fC TokenState public constant tokenstatesethbtc_i = TokenState(0x042A7A0022A7695454ac5Be77a4860e50c9683fC); // https://etherscan.io/address/0x104eDF1da359506548BFc7c25bA1E28C16a70235 ProxyERC20 public constant proxysethbtc_i = ProxyERC20(0x104eDF1da359506548BFc7c25bA1E28C16a70235); // https://etherscan.io/address/0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124 MultiCollateralSynth public constant synthsdefi_i = MultiCollateralSynth(0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124); // https://etherscan.io/address/0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB TokenState public constant tokenstatesdefi_i = TokenState(0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB); // https://etherscan.io/address/0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B ProxyERC20 public constant proxysdefi_i = ProxyERC20(0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B); // https://etherscan.io/address/0xE60E71E47Ca405946CF147CA9d7589a851DBcddC Issuer public constant issuer_i = Issuer(0xE60E71E47Ca405946CF147CA9d7589a851DBcddC); // ---------------------------------- // NEW CONTRACTS DEPLOYED TO BE ADDED // ---------------------------------- // https://etherscan.io/address/0x977d0DD7eA212E9ca1dcD4Ec15cd7Ceb135fa68D address public constant new_OneNetAggregatorDebtRatio_contract = 0x977d0DD7eA212E9ca1dcD4Ec15cd7Ceb135fa68D; // https://etherscan.io/address/0x696c905F8F8c006cA46e9808fE7e00049507798F address public constant new_SystemStatus_contract = 0x696c905F8F8c006cA46e9808fE7e00049507798F; // https://etherscan.io/address/0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9 address public constant new_ExchangeRates_contract = 0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9; // https://etherscan.io/address/0xcf1405b18dBCEA2893Abe635c88359C75878B9e1 address public constant new_OneNetAggregatorIssuedSynths_contract = 0xcf1405b18dBCEA2893Abe635c88359C75878B9e1; // https://etherscan.io/address/0x3B2f389AeE480238A49E3A9985cd6815370712eB address public constant new_FeePool_contract = 0x3B2f389AeE480238A49E3A9985cd6815370712eB; // https://etherscan.io/address/0x74E9a032B04D9732E826eECFC5c7A1C183602FB1 address public constant new_Exchanger_contract = 0x74E9a032B04D9732E826eECFC5c7A1C183602FB1; // https://etherscan.io/address/0xeAcaEd9581294b1b5cfb6B941d4B8B81B2005437 address public constant new_ExchangeCircuitBreaker_contract = 0xeAcaEd9581294b1b5cfb6B941d4B8B81B2005437; // https://etherscan.io/address/0x1620Aa736939597891C1940CF0d28b82566F9390 address public constant new_DebtCache_contract = 0x1620Aa736939597891C1940CF0d28b82566F9390; // https://etherscan.io/address/0xc51f137e19F1ae6944887388FD12b2b6dFD12594 address public constant new_SynthetixBridgeToOptimism_contract = 0xc51f137e19F1ae6944887388FD12b2b6dFD12594; // https://etherscan.io/address/0xE60E71E47Ca405946CF147CA9d7589a851DBcddC address public constant new_Issuer_contract = 0xE60E71E47Ca405946CF147CA9d7589a851DBcddC; // https://etherscan.io/address/0x7df9b3f8f1C011D8BD707430e97E747479DD532a address public constant new_SynthsUSD_contract = 0x7df9b3f8f1C011D8BD707430e97E747479DD532a; // https://etherscan.io/address/0x1b06a00Df0B27E7871E753720D4917a7D1aac68b address public constant new_SynthsEUR_contract = 0x1b06a00Df0B27E7871E753720D4917a7D1aac68b; // https://etherscan.io/address/0xB82f11f3168Ece7D56fe6a5679567948090de7C5 address public constant new_SynthsJPY_contract = 0xB82f11f3168Ece7D56fe6a5679567948090de7C5; // https://etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C address public constant new_SynthsAUD_contract = 0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C; // https://etherscan.io/address/0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf address public constant new_SynthsGBP_contract = 0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf; // https://etherscan.io/address/0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d address public constant new_SynthsCHF_contract = 0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d; // https://etherscan.io/address/0x527637bE27640d6C3e751d24DC67129A6d13E11C address public constant new_SynthsKRW_contract = 0x527637bE27640d6C3e751d24DC67129A6d13E11C; // https://etherscan.io/address/0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6 address public constant new_SynthsETH_contract = 0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6; // https://etherscan.io/address/0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6 address public constant new_SynthsBTC_contract = 0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6; // https://etherscan.io/address/0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6 address public constant new_SynthsLINK_contract = 0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6; // https://etherscan.io/address/0xB34F4d7c207D8979D05EDb0F63f174764Bd67825 address public constant new_SynthsADA_contract = 0xB34F4d7c207D8979D05EDb0F63f174764Bd67825; // https://etherscan.io/address/0x95aE43E5E96314E4afffcf19D9419111cd11169e address public constant new_SynthsAAVE_contract = 0x95aE43E5E96314E4afffcf19D9419111cd11169e; // https://etherscan.io/address/0x27b45A4208b87A899009f45888139882477Acea5 address public constant new_SynthsDOT_contract = 0x27b45A4208b87A899009f45888139882477Acea5; // https://etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662 address public constant new_SynthsETHBTC_contract = 0x6DF798ec713b33BE823b917F27820f2aA0cf7662; // https://etherscan.io/address/0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124 address public constant new_SynthsDEFI_contract = 0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124; // https://etherscan.io/address/0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7 address public constant new_FuturesMarketManager_contract = 0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7; function migrate2() external { // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sUSD(); // Ensure the sUSD synth can write to its TokenState; tokenstatesusd_i.setAssociatedContract(new_SynthsUSD_contract); // Ensure the sUSD synth Proxy is correctly connected to the Synth; proxysusd_i.setTarget(Proxyable(new_SynthsUSD_contract)); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sEUR(); // Ensure the sEUR synth can write to its TokenState; tokenstateseur_i.setAssociatedContract(new_SynthsEUR_contract); // Ensure the sEUR synth Proxy is correctly connected to the Synth; proxyseur_i.setTarget(Proxyable(new_SynthsEUR_contract)); // Ensure the ExchangeRates contract has the feed for sEUR; exchangerates_i.addAggregator("sEUR", 0xb49f677943BC038e9857d61E7d053CaA2C1734C1); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sJPY(); // Ensure the sJPY synth can write to its TokenState; tokenstatesjpy_i.setAssociatedContract(new_SynthsJPY_contract); // Ensure the sJPY synth Proxy is correctly connected to the Synth; proxysjpy_i.setTarget(Proxyable(new_SynthsJPY_contract)); // Ensure the ExchangeRates contract has the feed for sJPY; exchangerates_i.addAggregator("sJPY", 0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sAUD(); // Ensure the sAUD synth can write to its TokenState; tokenstatesaud_i.setAssociatedContract(new_SynthsAUD_contract); // Ensure the sAUD synth Proxy is correctly connected to the Synth; proxysaud_i.setTarget(Proxyable(new_SynthsAUD_contract)); // Ensure the ExchangeRates contract has the feed for sAUD; exchangerates_i.addAggregator("sAUD", 0x77F9710E7d0A19669A13c055F62cd80d313dF022); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sGBP(); // Ensure the sGBP synth can write to its TokenState; tokenstatesgbp_i.setAssociatedContract(new_SynthsGBP_contract); // Ensure the sGBP synth Proxy is correctly connected to the Synth; proxysgbp_i.setTarget(Proxyable(new_SynthsGBP_contract)); // Ensure the ExchangeRates contract has the feed for sGBP; exchangerates_i.addAggregator("sGBP", 0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sCHF(); // Ensure the sCHF synth can write to its TokenState; tokenstateschf_i.setAssociatedContract(new_SynthsCHF_contract); // Ensure the sCHF synth Proxy is correctly connected to the Synth; proxyschf_i.setTarget(Proxyable(new_SynthsCHF_contract)); // Ensure the ExchangeRates contract has the feed for sCHF; exchangerates_i.addAggregator("sCHF", 0x449d117117838fFA61263B61dA6301AA2a88B13A); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sKRW(); // Ensure the sKRW synth can write to its TokenState; tokenstateskrw_i.setAssociatedContract(new_SynthsKRW_contract); // Ensure the sKRW synth Proxy is correctly connected to the Synth; proxyskrw_i.setTarget(Proxyable(new_SynthsKRW_contract)); // Ensure the ExchangeRates contract has the feed for sKRW; exchangerates_i.addAggregator("sKRW", 0x01435677FB11763550905594A16B645847C1d0F3); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sBTC(); // Ensure the sBTC synth can write to its TokenState; tokenstatesbtc_i.setAssociatedContract(new_SynthsBTC_contract); // Ensure the sBTC synth Proxy is correctly connected to the Synth; proxysbtc_i.setTarget(Proxyable(new_SynthsBTC_contract)); // Ensure the ExchangeRates contract has the feed for sBTC; exchangerates_i.addAggregator("sBTC", 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sETH(); // Ensure the sETH synth can write to its TokenState; tokenstateseth_i.setAssociatedContract(new_SynthsETH_contract); // Ensure the sETH synth Proxy is correctly connected to the Synth; proxyseth_i.setTarget(Proxyable(new_SynthsETH_contract)); // Ensure the ExchangeRates contract has the feed for sETH; exchangerates_i.addAggregator("sETH", 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sLINK(); // Ensure the sLINK synth can write to its TokenState; tokenstateslink_i.setAssociatedContract(new_SynthsLINK_contract); // Ensure the sLINK synth Proxy is correctly connected to the Synth; proxyslink_i.setTarget(Proxyable(new_SynthsLINK_contract)); // Ensure the ExchangeRates contract has the feed for sLINK; exchangerates_i.addAggregator("sLINK", 0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sADA(); // Ensure the sADA synth can write to its TokenState; tokenstatesada_i.setAssociatedContract(new_SynthsADA_contract); // Ensure the sADA synth Proxy is correctly connected to the Synth; proxysada_i.setTarget(Proxyable(new_SynthsADA_contract)); // Ensure the ExchangeRates contract has the feed for sADA; exchangerates_i.addAggregator("sADA", 0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sAAVE(); // Ensure the sAAVE synth can write to its TokenState; tokenstatesaave_i.setAssociatedContract(new_SynthsAAVE_contract); // Ensure the sAAVE synth Proxy is correctly connected to the Synth; proxysaave_i.setTarget(Proxyable(new_SynthsAAVE_contract)); // Ensure the ExchangeRates contract has the feed for sAAVE; exchangerates_i.addAggregator("sAAVE", 0x547a514d5e3769680Ce22B2361c10Ea13619e8a9); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sDOT(); // Ensure the sDOT synth can write to its TokenState; tokenstatesdot_i.setAssociatedContract(new_SynthsDOT_contract); // Ensure the sDOT synth Proxy is correctly connected to the Synth; proxysdot_i.setTarget(Proxyable(new_SynthsDOT_contract)); // Ensure the ExchangeRates contract has the feed for sDOT; exchangerates_i.addAggregator("sDOT", 0x1C07AFb8E2B827c5A4739C6d59Ae3A5035f28734); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sETHBTC(); // Ensure the sETHBTC synth can write to its TokenState; tokenstatesethbtc_i.setAssociatedContract(new_SynthsETHBTC_contract); // Ensure the sETHBTC synth Proxy is correctly connected to the Synth; proxysethbtc_i.setTarget(Proxyable(new_SynthsETHBTC_contract)); // Ensure the ExchangeRates contract has the feed for sETHBTC; exchangerates_i.addAggregator("sETHBTC", 0xAc559F25B1619171CbC396a50854A3240b6A4e99); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sDEFI(); // Ensure the sDEFI synth can write to its TokenState; tokenstatesdefi_i.setAssociatedContract(new_SynthsDEFI_contract); // Ensure the sDEFI synth Proxy is correctly connected to the Synth; proxysdefi_i.setTarget(Proxyable(new_SynthsDEFI_contract)); // Ensure the ExchangeRates contract has the feed for sDEFI; exchangerates_i.addAggregator("sDEFI", 0xa8E875F94138B0C5b51d1e1d5dE35bbDdd28EA87); // Add synths to the Issuer contract - batch 1; issuer_addSynths_96(); // SIP-120 Set the DEX price aggregator (uniswap TWAP oracle reader); exchangerates_i.setDexPriceAggregator(IDexPriceAggregator(0xf120F029Ac143633d1942e48aE2Dfa2036C5786c)); } function copyTotalSupplyFrom_sUSD() internal { // https://etherscan.io/address/0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA; Synth existingSynth = Synth(0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA); // https://etherscan.io/address/0x7df9b3f8f1C011D8BD707430e97E747479DD532a; Synth newSynth = Synth(0x7df9b3f8f1C011D8BD707430e97E747479DD532a); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sEUR() internal { // https://etherscan.io/address/0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0; Synth existingSynth = Synth(0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0); // https://etherscan.io/address/0x1b06a00Df0B27E7871E753720D4917a7D1aac68b; Synth newSynth = Synth(0x1b06a00Df0B27E7871E753720D4917a7D1aac68b); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sJPY() internal { // https://etherscan.io/address/0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A; Synth existingSynth = Synth(0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A); // https://etherscan.io/address/0xB82f11f3168Ece7D56fe6a5679567948090de7C5; Synth newSynth = Synth(0xB82f11f3168Ece7D56fe6a5679567948090de7C5); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sAUD() internal { // https://etherscan.io/address/0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827; Synth existingSynth = Synth(0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827); // https://etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C; Synth newSynth = Synth(0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sGBP() internal { // https://etherscan.io/address/0xde3892383965FBa6eC434bE6350F85f140098708; Synth existingSynth = Synth(0xde3892383965FBa6eC434bE6350F85f140098708); // https://etherscan.io/address/0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf; Synth newSynth = Synth(0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sCHF() internal { // https://etherscan.io/address/0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D; Synth existingSynth = Synth(0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D); // https://etherscan.io/address/0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d; Synth newSynth = Synth(0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sKRW() internal { // https://etherscan.io/address/0xe2f532c389deb5E42DCe53e78A9762949A885455; Synth existingSynth = Synth(0xe2f532c389deb5E42DCe53e78A9762949A885455); // https://etherscan.io/address/0x527637bE27640d6C3e751d24DC67129A6d13E11C; Synth newSynth = Synth(0x527637bE27640d6C3e751d24DC67129A6d13E11C); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sBTC() internal { // https://etherscan.io/address/0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353; Synth existingSynth = Synth(0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353); // https://etherscan.io/address/0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6; Synth newSynth = Synth(0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sETH() internal { // https://etherscan.io/address/0xc70B42930BD8D30A79B55415deC3be60827559f7; Synth existingSynth = Synth(0xc70B42930BD8D30A79B55415deC3be60827559f7); // https://etherscan.io/address/0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6; Synth newSynth = Synth(0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sLINK() internal { // https://etherscan.io/address/0x3FFE35c3d412150C3B91d3E22eBA60E16030C608; Synth existingSynth = Synth(0x3FFE35c3d412150C3B91d3E22eBA60E16030C608); // https://etherscan.io/address/0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6; Synth newSynth = Synth(0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sADA() internal { // https://etherscan.io/address/0x8f9fa817200F5B95f9572c8Acf2b31410C00335a; Synth existingSynth = Synth(0x8f9fa817200F5B95f9572c8Acf2b31410C00335a); // https://etherscan.io/address/0xB34F4d7c207D8979D05EDb0F63f174764Bd67825; Synth newSynth = Synth(0xB34F4d7c207D8979D05EDb0F63f174764Bd67825); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sAAVE() internal { // https://etherscan.io/address/0x0705F0716b12a703d4F8832Ec7b97C61771f0361; Synth existingSynth = Synth(0x0705F0716b12a703d4F8832Ec7b97C61771f0361); // https://etherscan.io/address/0x95aE43E5E96314E4afffcf19D9419111cd11169e; Synth newSynth = Synth(0x95aE43E5E96314E4afffcf19D9419111cd11169e); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sDOT() internal { // https://etherscan.io/address/0xfA60918C4417b64E722ca15d79C751c1f24Ab995; Synth existingSynth = Synth(0xfA60918C4417b64E722ca15d79C751c1f24Ab995); // https://etherscan.io/address/0x27b45A4208b87A899009f45888139882477Acea5; Synth newSynth = Synth(0x27b45A4208b87A899009f45888139882477Acea5); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sETHBTC() internal { // https://etherscan.io/address/0xcc3aab773e2171b2E257Ee17001400eE378aa52B; Synth existingSynth = Synth(0xcc3aab773e2171b2E257Ee17001400eE378aa52B); // https://etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662; Synth newSynth = Synth(0x6DF798ec713b33BE823b917F27820f2aA0cf7662); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sDEFI() internal { // https://etherscan.io/address/0xe59dFC746D566EB40F92ed0B162004e24E3AC932; Synth existingSynth = Synth(0xe59dFC746D566EB40F92ed0B162004e24E3AC932); // https://etherscan.io/address/0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124; Synth newSynth = Synth(0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124); newSynth.setTotalSupply(existingSynth.totalSupply()); } function issuer_addSynths_96() internal { ISynth[] memory issuer_addSynths_synthsToAdd_96_0 = new ISynth[](15); issuer_addSynths_synthsToAdd_96_0[0] = ISynth(new_SynthsUSD_contract); issuer_addSynths_synthsToAdd_96_0[1] = ISynth(new_SynthsEUR_contract); issuer_addSynths_synthsToAdd_96_0[2] = ISynth(new_SynthsJPY_contract); issuer_addSynths_synthsToAdd_96_0[3] = ISynth(new_SynthsAUD_contract); issuer_addSynths_synthsToAdd_96_0[4] = ISynth(new_SynthsGBP_contract); issuer_addSynths_synthsToAdd_96_0[5] = ISynth(new_SynthsCHF_contract); issuer_addSynths_synthsToAdd_96_0[6] = ISynth(new_SynthsKRW_contract); issuer_addSynths_synthsToAdd_96_0[7] = ISynth(new_SynthsBTC_contract); issuer_addSynths_synthsToAdd_96_0[8] = ISynth(new_SynthsETH_contract); issuer_addSynths_synthsToAdd_96_0[9] = ISynth(new_SynthsLINK_contract); issuer_addSynths_synthsToAdd_96_0[10] = ISynth(new_SynthsADA_contract); issuer_addSynths_synthsToAdd_96_0[11] = ISynth(new_SynthsAAVE_contract); issuer_addSynths_synthsToAdd_96_0[12] = ISynth(new_SynthsDOT_contract); issuer_addSynths_synthsToAdd_96_0[13] = ISynth(new_SynthsETHBTC_contract); issuer_addSynths_synthsToAdd_96_0[14] = ISynth(new_SynthsDEFI_contract); issuer_i.addSynths(issuer_addSynths_synthsToAdd_96_0); } function addressresolver_importAddresses_0() external { bytes32[] memory addressresolver_importAddresses_names_0_0 = new bytes32[](28); addressresolver_importAddresses_names_0_0[0] = bytes32("OneNetAggregatorDebtRatio"); addressresolver_importAddresses_names_0_0[1] = bytes32("SystemStatus"); addressresolver_importAddresses_names_0_0[2] = bytes32("ExchangeRates"); addressresolver_importAddresses_names_0_0[3] = bytes32("OneNetAggregatorIssuedSynths"); addressresolver_importAddresses_names_0_0[4] = bytes32("FeePool"); addressresolver_importAddresses_names_0_0[5] = bytes32("Exchanger"); addressresolver_importAddresses_names_0_0[6] = bytes32("ExchangeCircuitBreaker"); addressresolver_importAddresses_names_0_0[7] = bytes32("DebtCache"); addressresolver_importAddresses_names_0_0[8] = bytes32("SynthetixBridgeToOptimism"); addressresolver_importAddresses_names_0_0[9] = bytes32("Issuer"); addressresolver_importAddresses_names_0_0[10] = bytes32("SynthsUSD"); addressresolver_importAddresses_names_0_0[11] = bytes32("SynthsEUR"); addressresolver_importAddresses_names_0_0[12] = bytes32("SynthsJPY"); addressresolver_importAddresses_names_0_0[13] = bytes32("SynthsAUD"); addressresolver_importAddresses_names_0_0[14] = bytes32("SynthsGBP"); addressresolver_importAddresses_names_0_0[15] = bytes32("SynthsCHF"); addressresolver_importAddresses_names_0_0[16] = bytes32("SynthsKRW"); addressresolver_importAddresses_names_0_0[17] = bytes32("SynthsETH"); addressresolver_importAddresses_names_0_0[18] = bytes32("SynthsBTC"); addressresolver_importAddresses_names_0_0[19] = bytes32("SynthsLINK"); addressresolver_importAddresses_names_0_0[20] = bytes32("SynthsADA"); addressresolver_importAddresses_names_0_0[21] = bytes32("SynthsAAVE"); addressresolver_importAddresses_names_0_0[22] = bytes32("SynthsDOT"); addressresolver_importAddresses_names_0_0[23] = bytes32("SynthsETHBTC"); addressresolver_importAddresses_names_0_0[24] = bytes32("SynthsDEFI"); addressresolver_importAddresses_names_0_0[25] = bytes32("FuturesMarketManager"); addressresolver_importAddresses_names_0_0[26] = bytes32("ext:AggregatorIssuedSynths"); addressresolver_importAddresses_names_0_0[27] = bytes32("ext:AggregatorDebtRatio"); address[] memory addressresolver_importAddresses_destinations_0_1 = new address[](28); addressresolver_importAddresses_destinations_0_1[0] = address(new_OneNetAggregatorDebtRatio_contract); addressresolver_importAddresses_destinations_0_1[1] = address(new_SystemStatus_contract); addressresolver_importAddresses_destinations_0_1[2] = address(new_ExchangeRates_contract); addressresolver_importAddresses_destinations_0_1[3] = address(new_OneNetAggregatorIssuedSynths_contract); addressresolver_importAddresses_destinations_0_1[4] = address(new_FeePool_contract); addressresolver_importAddresses_destinations_0_1[5] = address(new_Exchanger_contract); addressresolver_importAddresses_destinations_0_1[6] = address(new_ExchangeCircuitBreaker_contract); addressresolver_importAddresses_destinations_0_1[7] = address(new_DebtCache_contract); addressresolver_importAddresses_destinations_0_1[8] = address(new_SynthetixBridgeToOptimism_contract); addressresolver_importAddresses_destinations_0_1[9] = address(new_Issuer_contract); addressresolver_importAddresses_destinations_0_1[10] = address(new_SynthsUSD_contract); addressresolver_importAddresses_destinations_0_1[11] = address(new_SynthsEUR_contract); addressresolver_importAddresses_destinations_0_1[12] = address(new_SynthsJPY_contract); addressresolver_importAddresses_destinations_0_1[13] = address(new_SynthsAUD_contract); addressresolver_importAddresses_destinations_0_1[14] = address(new_SynthsGBP_contract); addressresolver_importAddresses_destinations_0_1[15] = address(new_SynthsCHF_contract); addressresolver_importAddresses_destinations_0_1[16] = address(new_SynthsKRW_contract); addressresolver_importAddresses_destinations_0_1[17] = address(new_SynthsETH_contract); addressresolver_importAddresses_destinations_0_1[18] = address(new_SynthsBTC_contract); addressresolver_importAddresses_destinations_0_1[19] = address(new_SynthsLINK_contract); addressresolver_importAddresses_destinations_0_1[20] = address(new_SynthsADA_contract); addressresolver_importAddresses_destinations_0_1[21] = address(new_SynthsAAVE_contract); addressresolver_importAddresses_destinations_0_1[22] = address(new_SynthsDOT_contract); addressresolver_importAddresses_destinations_0_1[23] = address(new_SynthsETHBTC_contract); addressresolver_importAddresses_destinations_0_1[24] = address(new_SynthsDEFI_contract); addressresolver_importAddresses_destinations_0_1[25] = address(new_FuturesMarketManager_contract); addressresolver_importAddresses_destinations_0_1[26] = address(new_OneNetAggregatorIssuedSynths_contract); addressresolver_importAddresses_destinations_0_1[27] = address(new_OneNetAggregatorDebtRatio_contract); addressresolver_i.importAddresses( addressresolver_importAddresses_names_0_0, addressresolver_importAddresses_destinations_0_1 ); } function addressresolver_rebuildCaches_1() external { MixinResolver[] memory addressresolver_rebuildCaches_destinations_1_0 = new MixinResolver[](20); addressresolver_rebuildCaches_destinations_1_0[0] = MixinResolver(0xDA4eF8520b1A57D7d63f1E249606D1A459698876); addressresolver_rebuildCaches_destinations_1_0[1] = MixinResolver(0xAD95C918af576c82Df740878C3E983CBD175daB6); addressresolver_rebuildCaches_destinations_1_0[2] = MixinResolver(new_FeePool_contract); addressresolver_rebuildCaches_destinations_1_0[3] = MixinResolver(0xE95A536cF5C7384FF1ef54819Dc54E03d0FF1979); addressresolver_rebuildCaches_destinations_1_0[4] = MixinResolver(new_DebtCache_contract); addressresolver_rebuildCaches_destinations_1_0[5] = MixinResolver(new_Exchanger_contract); addressresolver_rebuildCaches_destinations_1_0[6] = MixinResolver(new_ExchangeCircuitBreaker_contract); addressresolver_rebuildCaches_destinations_1_0[7] = MixinResolver(new_Issuer_contract); addressresolver_rebuildCaches_destinations_1_0[8] = MixinResolver(new_SynthsUSD_contract); addressresolver_rebuildCaches_destinations_1_0[9] = MixinResolver(new_SynthsEUR_contract); addressresolver_rebuildCaches_destinations_1_0[10] = MixinResolver(new_SynthsJPY_contract); addressresolver_rebuildCaches_destinations_1_0[11] = MixinResolver(new_SynthsAUD_contract); addressresolver_rebuildCaches_destinations_1_0[12] = MixinResolver(new_SynthsGBP_contract); addressresolver_rebuildCaches_destinations_1_0[13] = MixinResolver(new_SynthsCHF_contract); addressresolver_rebuildCaches_destinations_1_0[14] = MixinResolver(new_SynthsKRW_contract); addressresolver_rebuildCaches_destinations_1_0[15] = MixinResolver(new_SynthsBTC_contract); addressresolver_rebuildCaches_destinations_1_0[16] = MixinResolver(new_SynthsETH_contract); addressresolver_rebuildCaches_destinations_1_0[17] = MixinResolver(new_SynthsLINK_contract); addressresolver_rebuildCaches_destinations_1_0[18] = MixinResolver(new_SynthsADA_contract); addressresolver_rebuildCaches_destinations_1_0[19] = MixinResolver(new_SynthsAAVE_contract); addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_1_0); } function addressresolver_rebuildCaches_2() external { MixinResolver[] memory addressresolver_rebuildCaches_destinations_2_0 = new MixinResolver[](16); addressresolver_rebuildCaches_destinations_2_0[0] = MixinResolver(new_SynthsDOT_contract); addressresolver_rebuildCaches_destinations_2_0[1] = MixinResolver(new_SynthsETHBTC_contract); addressresolver_rebuildCaches_destinations_2_0[2] = MixinResolver(new_SynthsDEFI_contract); addressresolver_rebuildCaches_destinations_2_0[3] = MixinResolver(0x5c8344bcdC38F1aB5EB5C1d4a35DdEeA522B5DfA); addressresolver_rebuildCaches_destinations_2_0[4] = MixinResolver(0xaa03aB31b55DceEeF845C8d17890CC61cD98eD04); addressresolver_rebuildCaches_destinations_2_0[5] = MixinResolver(0x1F2c3a1046c32729862fcB038369696e3273a516); addressresolver_rebuildCaches_destinations_2_0[6] = MixinResolver(0x7C22547779c8aa41bAE79E03E8383a0BefBCecf0); addressresolver_rebuildCaches_destinations_2_0[7] = MixinResolver(0xC1AAE9d18bBe386B102435a8632C8063d31e747C); addressresolver_rebuildCaches_destinations_2_0[8] = MixinResolver(0x067e398605E84F2D0aEEC1806e62768C5110DCc6); addressresolver_rebuildCaches_destinations_2_0[9] = MixinResolver(new_ExchangeRates_contract); addressresolver_rebuildCaches_destinations_2_0[10] = MixinResolver(new_SynthetixBridgeToOptimism_contract); addressresolver_rebuildCaches_destinations_2_0[11] = MixinResolver(0x02f9bC46beD33acdB9cb002fe346734CeF8a9480); addressresolver_rebuildCaches_destinations_2_0[12] = MixinResolver(0x62922670313bf6b41C580143d1f6C173C5C20019); addressresolver_rebuildCaches_destinations_2_0[13] = MixinResolver(0x89FCb32F29e509cc42d0C8b6f058C993013A843F); addressresolver_rebuildCaches_destinations_2_0[14] = MixinResolver(0xe533139Af961c9747356D947838c98451015e234); addressresolver_rebuildCaches_destinations_2_0[15] = MixinResolver(0x7A3d898b717e50a96fd8b232E9d15F0A547A7eeb); addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_2_0); } }
https:etherscan.io/address/0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827; https:etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C;
function copyTotalSupplyFrom_sAUD() internal { Synth existingSynth = Synth(0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827); Synth newSynth = Synth(0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C); newSynth.setTotalSupply(existingSynth.totalSupply()); }
2,494,160
pragma solidity ^0.4.18; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract ERC20 { string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } } /******************************************/ /* RUSH TOKEN STARTS HERE */ /******************************************/ contract TestRushCoin is ERC20 { /* Initializes contract with initial supply tokens to the creator of the contract */ function TestRushCoin() ERC20(5000000000, "Test Rush Coin", "TRUSH") public {} function multisend(address[] dests, uint256[] values) public returns (uint256) { uint256 i = 0; while (i < dests.length) { transfer(dests[i], values[i]); i += 1; } return(i); } }
Initializes contract with initial supply tokens to the creator of the contract /
function TestRushCoin() ERC20(5000000000, "Test Rush Coin", "TRUSH") public {}
2,319,147
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title 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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; 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 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 Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract WaltixToken is MintableToken, PausableToken { string public constant name = "Waltix Token"; string public constant symbol = "WLTX"; uint32 public constant decimals = 3; function WaltixToken() public { // --- сразу ставим токен на паузу // чтобы на этапе PreSale нельзя было переводить токены pause(); } }
--- сразу ставим токен на паузу чтобы на этапе PreSale нельзя было переводить токены
function WaltixToken() public { pause(); }
13,928,145
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interface/IGoat.sol"; import "./interface/IBarn.sol"; import "./interface/ITraits.sol"; import "./utils/Ownable.sol"; import "./utils/Pausable.sol"; import "./utils/ECDSA.sol"; import "./token/ERC721Enumerable.sol"; import "./EGG.sol"; contract Goat is IGoat, ERC721Enumerable, Ownable, Pausable { using ECDSA for bytes32; struct LastWrite { uint64 time; uint64 blockNum; } struct Whitelist { uint hasMinted; } event TortoiseStolen(address owner, uint256 tokenId, uint256 value); event GoatStolen(address owner, uint256 tokenId, uint256 value); uint256 public totalTortoiseMinted; uint256 public totalGoatMinted; uint256 public totalTortoiseStolen; uint256 public totalGoatStolen; // mint price uint256 public MINT_PRICE = .042069 ether; // max number of tokens that can be minted - 50000 in production uint256 public MAX_TOKENS; // number of tokens that can be claimed for free - 20% of MAX_TOKENS uint256 public PAID_TOKENS; // number of tokens have been minted so far uint16 public minted; // list of probabilities for each trait type // 0 - 9 are associated with Tortoise, 10 - 18 are associated with Goats uint8[][20] public rarities; // list of aliases for Walker's Alias algorithm // 0 - 9 are associated with Tortoise, 10 - 18 are associated with Goats uint8[][20] public aliases; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => GoatTortoise) public tokenTraits; // mapping from hashed(tokenTrait) to the tokenId it's associated with // used to ensure there are no duplicates mapping(uint256 => uint256) public existingCombinations; // Tracks the last block and timestamp that a caller has written to state. // Disallow some access to functions if they occur while a change is being written. mapping(address => LastWrite) private lastWrite; // address => User mapping(address => Whitelist) public whitelist; // address => allowedToCallFunctions mapping(address => bool) private admins; // reference to the ProtectedIsland for choosing random Goat thieves IProtectedIsland public protectedIsland; // reference to $EGG for burning on mint EGG public egg; // reference to Traits ITraits public traits; // boolean => checks if the earlyAccessMintSale is open or closed bool public earlyAccessMintSale = false; // boolean => checks if the publicMintSale is open or closed bool public publicMintSale = false; // bytes32 -> DomainSeparator bytes32 public DOMAIN_SEPARATOR; // bytes32 -> PRESALE_TYPEHASH bytes32 public constant PRESALE_TYPEHASH = keccak256("EarlyAccess(address buyer,uint256 maxCount)"); // address -> whitelist signer address public whitelistSigner; // address -> old goat contract to interact with IERC721 public oldGoatContract; /** * instantiates contract and rarity tables */ constructor(address _egg, address _traits, uint256 _maxTokens, address _whitelistSigner, IERC721 _oldGoatContract) ERC721("Enchanted Game", 'EGAME') { egg = EGG(_egg); traits = ITraits(_traits); MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; whitelistSigner = _whitelistSigner; oldGoatContract = _oldGoatContract; // I know this looks weird but it saves users gas by making lookup O(1) // A.J. Walker's Alias Algorithm // Goat // Fur rarities[0] = [128, 77, 77, 128, 153, 128, 128, 128, 128, 128, 230, 255, 230, 230, 255, 77, 153, 153, 204, 128]; aliases[0] = [14, 0, 10, 10, 10, 10, 11, 11, 11, 11, 14, 11, 14, 14, 14, 12, 12, 13, 13, 13]; // Skin rarities[1] = [255]; aliases[1] = [0]; // Ears rarities[2] = [216, 230, 230, 207, 172, 46, 255, 172, 92]; aliases[2] = [6, 0, 0, 0, 0, 0, 6, 0, 6]; // Eyes rarities[3] = [255, 128, 255, 191, 255, 128, 191, 255, 128, 128]; aliases[3] = [0, 0, 2, 0, 4, 0, 0, 7, 0, 7]; // shell rarities[4] = [255]; aliases[4] = [0]; // face rarities[5] = [255]; aliases[5] = [0]; // neck rarities[6] = [179, 217, 140, 204, 77, 191, 128, 255, 115, 153]; aliases[6] = [7, 0, 0, 7, 0, 3, 3, 7, 3, 3]; // feet rarities[7] = [255, 255, 255, 255, 191, 255, 128, 128, 64, 64]; aliases[7] = [0, 1, 2, 3, 5, 5, 0, 4, 4, 5]; // fertilityIndex rarities[8] = [102, 204, 153, 255]; aliases[8] = [2, 3, 3, 3]; // Accessory rarities[9] = [255]; aliases[9] = [0]; // Tortoise // Fur rarities[10] = [255]; aliases[10] = [0]; // Skin rarities[11] = [227, 227, 255, 255, 255, 170, 170, 227, 255, 227, 227, 227, 198, 198, 198, 227, 255, 198, 198, 142]; aliases[11] = [8, 0, 2, 3, 4, 0, 12, 0, 8, 0, 0, 0, 15, 0, 0, 16, 16, 0, 0, 6]; // Ears rarities[12] = [255]; aliases[12] = [0]; // Eyes rarities[13] = [255]; aliases[13] = [0]; // shell rarities[14] = [255, 113, 57, 255, 142, 227, 227, 113, 57, 28, 227, 142, 170, 255, 113, 113, 170, 255, 142, 227]; aliases[14] = [0, 12, 13, 3, 16, 17, 0, 1, 1, 2, 3, 3, 17, 13, 3, 4, 17, 17, 5, 12]; // face rarities[15] = [99, 241, 71, 71, 255, 170, 142, 142, 255, 255]; aliases[15] = [9, 9, 0, 1, 4, 4, 4, 4, 8, 9]; // neck rarities[16] = [255]; aliases[16] = [0]; // feet rarities[17] = [227, 170, 255, 142, 142, 198, 227, 255, 142, 142]; aliases[17] = [2, 5, 2, 0, 0, 6, 7, 7, 0, 1]; // fertilityIndex rarities[18] = [57, 170, 142, 255]; aliases[18] = [2, 3, 3, 3]; // Accessory rarities[19] = [198, 227, 255, 227, 255, 255, 227, 255, 255, 198]; aliases[19] = [1, 4, 2, 5, 4, 5, 2, 7, 8, 3]; // Early Access stuff uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes("ECC")), keccak256(bytes("1")), chainId, address(this) ) ); } /** CRITICAL TO SETUP / MODIFIERS */ modifier disallowIfStateIsChanging() { // frens can always call whenever they want :) require(admins[_msgSender()] || lastWrite[tx.origin].blockNum < block.number, "hmmmm what doing?"); _; } /** * Mint */ function _mint(uint256 amount, bool stake) internal { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); } else { require(msg.value == 0); } uint256 totalEggCost = 0; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted, lastWrite[tx.origin].time, lastWrite[tx.origin].blockNum); generate(minted, seed, lastWrite[tx.origin]); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); // check if the recipient is the sender if (recipient != _msgSender()) { // token is stolen! if (tokenTraits[minted].isTortoise) { totalTortoiseStolen += 1; emit TortoiseStolen(_msgSender(), minted, block.timestamp); } else { totalGoatStolen += 1; emit GoatStolen(_msgSender(), minted, block.timestamp); } } } else { _safeMint(address(protectedIsland), minted); tokenIds[i] = minted; } // check token traits for tortoise or goat and increase mint amount totalEggCost += mintCost(minted); } if (totalEggCost > 0) egg.burn(_msgSender(), totalEggCost); if (stake) protectedIsland.addManyToProtectedIslandAndPack(_msgSender(), tokenIds); // update lastWrite for sender updateOriginAccess(); } /** * mint a token - 90% Tortoise, 10% Goats * The first 20% are free to claim, the remaining cost $EGG */ function publicMint(uint256 _amount, bool _stake) external payable whenNotPaused { require(publicMintSale, "Public sale is not active"); _mint(_amount, _stake); } /** * mint a token - 90% Tortoise, 10% Goats * The first 20% are free to claim, the remaining cost $EGG */ function earlyAccessMint(uint256 _amount, uint256 maxCount, bytes memory signature, bool _stake) external payable whenNotPaused { require(earlyAccessMintSale, "Early access is not active"); // Verify EIP-712 signature bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PRESALE_TYPEHASH, msg.sender, maxCount)))); address recoveredAddress = digest.recover(signature); // Is the signature the same as the whitelist signer if yes? your able to mint. require(recoveredAddress != address(0) && recoveredAddress == address(whitelistSigner), "Invalid signature"); require((whitelist[msg.sender].hasMinted + _amount) <= maxCount, "Early Access max count exceeded"); whitelist[msg.sender].hasMinted += _amount; _mint(_amount, _stake); } function swapTokens(uint[] memory _tokenIds) external whenNotPaused { uint256 amount = _tokenIds.length; uint256 oldBalance = oldGoatContract.balanceOf(_msgSender()); require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); // Does the user have enough balance to make the swap work. require(oldBalance > 0, "You don't own any of the old tokens"); // Does the user approved for all. require(oldGoatContract.isApprovedForAll(_msgSender(), address(this)), 'Not approved for all'); uint256 seed; for (uint i = 0; i < amount; i++) { // Does the user own the given tokens? require(oldGoatContract.ownerOf(_tokenIds[i]) == _msgSender(), "hmmm not your tokens?"); oldGoatContract.safeTransferFrom(_msgSender(), address(0xdead), _tokenIds[i]); minted++; seed = random(minted, lastWrite[tx.origin].time, lastWrite[tx.origin].blockNum); generate(minted, seed, lastWrite[tx.origin]); _safeMint(_msgSender(), minted); } // update lastWrite for sender updateOriginAccess(); } /** * the first 20% are paid in ETH * the next 20% are 20000 $EGG * the next 40% are 40000 $EGG * the final 20% are 80000 $EGG * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId) public view returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; if (tokenId <= MAX_TOKENS * 2 / 5) return 20000 ether; if (tokenId <= MAX_TOKENS * 4 / 5) return 40000 ether; return 80000 ether; } /** * Updates `lastWrite` */ function updateOriginAccess() internal { lastWrite[tx.origin].blockNum = uint64(block.number); lastWrite[tx.origin].time = uint64(block.number); } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { // Hardcode the ProtectedIsland's approval so that users don't have to waste gas approving if (_msgSender() != address(protectedIsland)) require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** INTERNAL */ /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed, LastWrite memory lw) internal returns (GoatTortoise memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; if (t.isTortoise) { totalTortoiseMinted += 1; } else { totalGoatMinted += 1; } return t; } return generate(tokenId, random(seed, lw.time, lw.blockNum), lw); } /** * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup * ensuring O(1) instead of O(n) reduces mint cost by more than 50% * probability & alias tables are generated off-chain beforehand * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[traitType].length); if (seed >> 8 < rarities[traitType][trait]) return trait; return aliases[traitType][trait]; } /** * the first 20% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked Goat * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Goat thief's owner) */ function selectRecipient(uint256 seed) internal view returns (address) { if (minted <= PAID_TOKENS || ((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used address thief = protectedIsland.randomGoatOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); return thief; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of randomly selected traits */ function selectTraits(uint256 seed) internal view returns (GoatTortoise memory t) { t.isTortoise = (seed & 0xFFFF) % 10 != 0; uint8 shift = t.isTortoise ? 10 : 0; seed >>= 16; t.fur = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.skin = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; t.ears = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; t.eyes = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; t.shell = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; t.face = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; t.neck = selectTrait(uint16(seed & 0xFFFF), 6 + shift); seed >>= 16; t.feet = selectTrait(uint16(seed & 0xFFFF), 7 + shift); seed >>= 16; t.fertilityIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift); seed >>= 16; t.accessory = selectTrait(uint16(seed & 0xFFFF), 9 + shift); } /** * converts a struct to a 256 bit hash to check for uniqueness * @param s the struct to pack into a hash * @return the 256 bit hash of the struct */ function structToHash(GoatTortoise memory s) internal pure returns (uint256) { return uint256(bytes32( abi.encodePacked( s.isTortoise, s.fur, s.skin, s.ears, s.eyes, s.shell, s.face, s.neck, s.feet, s.accessory, s.fertilityIndex ) )); } /** * generates a pseudorandom number for picking traits. Uses point in time randomization to prevent abuse. */ function random(uint256 seed, uint64 timestamp, uint64 blockNumber) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(blockNumber > 1 ? blockNumber - 2 : blockNumber),// Different block than WnDGame to ensure if needing to re-randomize that it goes down a different path timestamp, seed ))); } function getTokenTraits(uint256 tokenId) external view override returns (GoatTortoise memory) { return tokenTraits[tokenId]; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } /// @notice Returns a list of all Goat IDs assigned to an address. /// @param _owner The owner whose Goats we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Owner's array looking for Goat(s) & Tortoise(s) belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { require(admins[_msgSender()] || lastWrite[_owner].blockNum < block.number, "hmmmm what doing?"); uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalSupply = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all goats have IDs starting at 1 and increasing // sequentially up to the totalGoats count. uint256 tokenId; for (tokenId = 1; tokenId <= totalSupply; tokenId++) { if (ownerOf(tokenId) == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * called after deployment so that the contract can get random Goat thieves * @param _protectedIsland the address of the ProtectedIsland */ function setProtectedIsland(address _protectedIsland) external onlyOwner { protectedIsland = IProtectedIsland(_protectedIsland); } /** * @param _oldGoatContract the address of the old goat contract */ function setOldGoatContract(IERC721 _oldGoatContract) external onlyOwner { oldGoatContract = _oldGoatContract; } /** * updates the number of tokens for sale */ function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } /** * Updates the mint price */ function setMintPrice(uint256 _mintPriceInWei) external onlyOwner { MINT_PRICE = _mintPriceInWei; } /** * Updates the max tokens; */ function setMaxTokens(uint256 _maxTokens) external onlyOwner { MAX_TOKENS = _maxTokens; } /** * updates the sales of the earlyAccess and the public sale */ function setSales(bool _earlyAccessMintSale, bool _publicMintSale) external onlyOwner { earlyAccessMintSale = _earlyAccessMintSale; publicMintSale = _publicMintSale; } /** * updates the sales of the earlyAccess and the public sale */ function setWhitelistSigner(address _whitelistSigner) external onlyOwner { whitelistSigner = _whitelistSigner; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return traits.tokenURI(tokenId); } /** OVERRIDES FOR SAFETY */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override(ERC721Enumerable) disallowIfStateIsChanging returns (uint256) { // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWrite[owner].blockNum < block.number, "hmmmm what doing?"); return super.tokenOfOwnerByIndex(owner, index); } function balanceOf(address owner) public view virtual override(ERC721) disallowIfStateIsChanging returns (uint256) { // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWrite[owner].blockNum < block.number, "hmmmm what doing?"); return super.balanceOf(owner); } function ownerOf(uint256 tokenId) public view virtual override(ERC721) disallowIfStateIsChanging returns (address) { address addr = super.ownerOf(tokenId); // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWrite[addr].blockNum < block.number, "hmmmm what doing?"); return addr; } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IGoat { // struct to store each token's traits struct GoatTortoise { bool isTortoise; uint8 fur; uint8 skin; uint8 ears; uint8 eyes; uint8 shell; uint8 face; uint8 neck; uint8 feet; uint8 accessory; uint8 fertilityIndex; } function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (GoatTortoise memory); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IProtectedIsland { function addManyToProtectedIslandAndPack(address account, uint16[] calldata tokenIds) external; function randomGoatOwner(uint256 seed) external view returns (address); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../utils/Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC721Enumerable.sol"; import "./ERC721.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./token/ERC20.sol"; import "./utils/Ownable.sol"; contract EGG is ERC20, Ownable { // a mapping from an address to whether or not it can mint / burn mapping(address => bool) controllers; constructor() ERC20("EGG", "EGG") { } /** * mints $EGG to a recipient * @param to the recipient of the $EGG * @param amount the amount of $EGG to mint */ function mint(address to, uint256 amount) external { require(controllers[msg.sender], "Only controllers can mint"); _mint(to, amount); } /** * burns $EGG from a holder * @param from the holder of the $EGG * @param amount the amount of $EGG to burn */ function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); } /** * enables an address to mint / burn * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC721.sol"; import "../interface/IERC721Receiver.sol"; import "../interface/IERC721Metadata.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "./ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC20.sol"; import "../interface/IERC20Metadata.sol"; import "../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
the first 20% (ETH purchases) go to the minter the remaining 80% have a 10% chance to be given to a random staked Goat seed a random value to select a recipient from return the address of the recipient (either the minter or the Goat thief's owner)/
function selectRecipient(uint256 seed) internal view returns (address) { if (thief == address(0x0)) return _msgSender(); return thief; }
595,637
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "../../erc/erc721/IERC721.sol"; import "../../erc/erc165/SupportsInterface.sol"; import "../../erc/erc721/IERC721TokenReceiver.sol"; import "../../common/Common.sol"; contract NFTBase is IERC721, Common, SupportsInterface { using AddressUtils for address; // region Constant string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROVED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008"; string constant TOKEN_NO_OWNER = "003009"; /// 如果一个智能合约可以接收NFT则返回该魔数 bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; // endregion // region Variable mapping(address => uint256) private ownerToNFTCount; mapping(uint256 => address) internal tokenIdToOwner; mapping(uint256 => address) internal tokenIdToApproval; /// <tokenOwner,<operator,bool>> /// tokenOwner 给 operator 的操作权限 mapping(address => mapping(address => bool)) internal ownerToOperators; // endregion // region Modifier modifier checkNFTValid(uint256 _tokenId){ require(tokenIdToOwner[_tokenId] != address(0), NOT_VALID_NFT); _; } modifier canTransfer(uint256 _tokenId) { address tokenOwner = tokenIdToOwner[_tokenId]; require( tokenOwner == msg.sender || tokenIdToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_APPROVED_OR_OPERATOR ); _; } modifier canOperate(uint256 _tokenId){ address tokenOwner = tokenIdToOwner[_tokenId]; require( tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_OR_OPERATOR ); _; } // endregion // region Function bytes4 internal constant SI = 0x01ffc9a9; constructor(){ supportedInterfaces[SI] = true; } // region Info function balanceOf(address _owner) external override view nz(_owner) returns (uint256) { return _getNFTCount(_owner); } function ownerOf(uint256 _tokenId) external view override returns (address _owner) { _owner = tokenIdToOwner[_tokenId]; require(_owner != address(0), NOT_VALID_NFT); } // endregion // region Transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata _data) external override { _safeTransferFrom(_from, _to, _tokenId, _data); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override { _safeTransferFrom(_from, _to, _tokenId, ""); } /// 仅限账户之间的资产转移 function transferFrom(address _from, address _to, uint256 _tokenId) external override nz(_from) nz(_to) canTransfer(_tokenId) checkNFTValid(_tokenId) { address tokenOwner = tokenIdToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); _transfer(_to, _tokenId); } // endregion // region Approval function approve(address _approved, uint256 _tokenId) external override nz(_approved) canOperate(_tokenId) checkNFTValid(_tokenId) { address tokenOwner = tokenIdToOwner[_tokenId]; require(_approved != tokenOwner, IS_OWNER); tokenIdToApproval[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } function getApproved(uint256 _tokenId) external view override checkNFTValid(_tokenId) returns (address) { return tokenIdToApproval[_tokenId]; } function setApprovalForAll(address _operator, bool _approved) external override nz(_operator) { ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function isApprovedForAll(address _owner, address _operator) external view override returns (bool) { return ownerToOperators[_owner][_operator]; } // endregion // endregion // region Base /// 内部转移NFT function _transfer(address _to, uint256 _tokenId) internal { address from = tokenIdToOwner[_tokenId]; require(from != address(0), TOKEN_NO_OWNER); _clearApproval(_tokenId); _removeNFT(from, _tokenId); _addNFT(_to, _tokenId); emit Transfer(from, _to, _tokenId); } function _mint(address _to, uint256 _tokenId) nz(_to) virtual internal { require(tokenIdToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); _addNFT(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } function _burn(uint256 _tokenId) internal virtual checkNFTValid(_tokenId) { address tokenOwner = tokenIdToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFT(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); } function _removeNFT(address _from, uint256 _tokenId) internal virtual { require(tokenIdToOwner[_tokenId] == _from, NOT_OWNER); ownerToNFTCount[_from] -= 1; delete tokenIdToOwner[_tokenId]; } function _addNFT(address _to, uint256 _tokenId) internal virtual { require(tokenIdToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); tokenIdToOwner[_tokenId] = _to; ownerToNFTCount[_to] += 1; } function _getNFTCount(address _owner) internal view virtual returns (uint256) { return ownerToNFTCount[_owner]; } function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private nz(_from) nz(_to) canTransfer(_tokenId) checkNFTValid(_tokenId) { address tokenOwner = tokenIdToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); _transfer(_to, _tokenId); // 如果是向合约转账,则需要等待合约接受的 if (_to.isContract()) { bytes4 res = IERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(res == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT); } } function _clearApproval(uint256 _tokenId) private { delete tokenIdToApproval[_tokenId]; } // endregion }
如果是向合约转账,则需要等待合约接受的
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private nz(_from) nz(_to) canTransfer(_tokenId) checkNFTValid(_tokenId) { address tokenOwner = tokenIdToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 res = IERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(res == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT); } }
5,385,065
pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../migration/SaiTubLike.sol"; import "../maker/ScdMcdMigration.sol"; import "../../constants/ConstantAddresses.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../maker/Manager.sol"; import "../maker/Join.sol"; contract AutomaticMigration is DSMath, ConstantAddresses { enum MigrationType { WITH_MKR, WITH_CONVERSION, WITH_DEBT } bytes32 SAI_ILK = 0x5341490000000000000000000000000000000000000000000000000000000000; uint MAX_GAS_PRICE = 50000000000; address public constant CUSTOM_MIGRATION_ACTIONS_PROXY = 0xc2429Ea56D3Eb580c9bda2A8ee08Fb8837Cb400c; struct Subscription { bytes32 cdpId; address owner; MigrationType migType; } address payable public owner; uint public changeIndex; mapping (address => bool) public approvedCallers; mapping (bytes32 => Subscription) public subscribers; ScdMcdMigration public migrationContract = ScdMcdMigration(SCD_MCD_MIGRATION); SaiTubLike public tubContract = SaiTubLike(TUB_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Manager public manager = Manager(MANAGER_ADDRESS); modifier isApprovedCaller() { require(approvedCallers[msg.sender]); _; } modifier onlyOwner() { require(owner == msg.sender); _; } event Subscribed(address indexed owner, bytes32 cdpId, MigrationType migType); event Unsubscribed(address indexed owner, bytes32 cdpId); event Migrated(bytes32 indexed oldCdp, uint indexed newCdp, address owner, uint timestamp); constructor() public { owner = msg.sender; approvedCallers[owner] = true; } function subscribe(bytes32 _cdpId, MigrationType _type) external { require(subscribers[_cdpId].owner == address(0x0)); require(isOwner(msg.sender, _cdpId)); subscribers[_cdpId] = Subscription({ cdpId: _cdpId, owner: msg.sender, migType: _type }); changeIndex++; emit Subscribed(msg.sender, _cdpId, _type); } function unsubscribe(bytes32 _cdpId) external { require(subscribers[_cdpId].owner != address(0x0)); require(isOwner(msg.sender, _cdpId)); delete subscribers[_cdpId]; changeIndex++; emit Unsubscribed(msg.sender, _cdpId); } function migrateFor(bytes32 _cdpId) external isApprovedCaller() { uint256 startGas = gasleft(); require(subscribers[_cdpId].cdpId == _cdpId); require(hasEnoughLiquidity(_cdpId)); MigrationType migType = subscribers[_cdpId].migType; if (migType == MigrationType.WITH_MKR) { DSProxyInterface(subscribers[_cdpId].owner).execute(CUSTOM_MIGRATION_ACTIONS_PROXY, abi.encodeWithSignature("migrate(address,bytes32)", SCD_MCD_MIGRATION, _cdpId)); } else if (migType == MigrationType.WITH_CONVERSION) { DSProxyInterface(subscribers[_cdpId].owner).execute(CUSTOM_MIGRATION_ACTIONS_PROXY, abi.encodeWithSignature("migratePayFeeWithGem(address,bytes32,address,address,uint256)", SCD_MCD_MIGRATION, _cdpId, OTC_ADDRESS, MAKER_DAI_ADDRESS, uint(-1))); } else if (migType == MigrationType.WITH_DEBT) { DSProxyInterface(subscribers[_cdpId].owner).execute(CUSTOM_MIGRATION_ACTIONS_PROXY, abi.encodeWithSignature("migratePayFeeWithDebt(address,bytes32,address,uint256,uint256)", SCD_MCD_MIGRATION, _cdpId, OTC_ADDRESS, uint(-1), 0)); } uint newVault = manager.last(subscribers[_cdpId].owner); uint currGasLeft = gasleft(); uint gasCost = calcTxCost(startGas, currGasLeft); // Draw eth to pay for gas cost DSProxyInterface(subscribers[_cdpId].owner).execute(PROXY_ACTIONS, abi.encodeWithSignature("freeETH(address,address,uint256,uint256)", MANAGER_ADDRESS, ETH_JOIN_ADDRESS, newVault, gasCost)); emit Migrated(_cdpId, newVault, subscribers[_cdpId].owner, block.timestamp); } function hasEnoughLiquidity(bytes32 _cdpId) public returns (bool) { uint migrationSai; uint cdpDebt; (, migrationSai) = vat.urns(SAI_ILK, SCD_MCD_MIGRATION); migrationSai = sub(migrationSai, 1000); cdpDebt = getDebt(_cdpId); return migrationSai > cdpDebt; } function getDebt(bytes32 _cdpId) public returns (uint cdpDebt) { ( , , cdpDebt, ) = tubContract.cups(_cdpId); } function calcTxCost(uint _startGas, uint _currGasLeft) public view returns(uint) { uint gasUsed = sub(_startGas, _currGasLeft); uint gasPrice = tx.gasprice > MAX_GAS_PRICE ? MAX_GAS_PRICE : tx.gasprice; gasUsed = add(gasUsed, 180000); // add for freeEth and log return mul(gasPrice, gasUsed); } function isOwner(address _owner, bytes32 _cdpId) internal view returns(bool) { require(tubContract.lad(_cdpId) == _owner); return true; } receive() external payable {} //////////////// Admin only functions ///////////////////////// /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } /// @notice Gets the Eth acumulated for the fee function getFee() public onlyOwner { owner.transfer(address(this).balance); } }
Removes a bot address so it can't call repay/boost _caller Bot address
function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; }
909,502
pragma solidity ^0.4.17; contract Lottery { address public manager; address[] public players; function Lottery() public { // init constructor manager = msg.sender; // global variable msg.sender. who created a contract } modifier restricted() { require(msg.sender == manager); // require executer be a manager who created a contract _; } function getPlayers() public view returns(address[]) { // all players in array helper func return players; } function enter() public payable { // enter a game, require payable require(msg.value > .01 ether); // min ammount to enter players.push(msg.sender); } function random() private view returns (uint){ return uint(keccak256(block.difficulty, now, players)); } function pickWinner() public restricted{ uint index = random() % players.length; // select pseudo-randomly a winner player players[index].transfer(this.balance); // send all money to winner players = new address[](0); // clear array of players } }
enter a game, require payable
function enter() public payable {
5,505,089
./full_match/1/0xc773ea6E2374b500F4F29d74b38d8e38930b1bBE/sources/contracts/nft_bridge/NFTBridge.sol
determine token parameters Verify that the correct interfaces are implemented first 32 bytes hold string length mload then loads the next word, i.e. the first 32 bytes of the strings NOTE: this means that we might end up with an invalid utf8 string (e.g. if we slice an emoji in half). The VAA payload specification doesn't require that these are valid utf8 strings, and it's cheaper to do any validation off-chain for presentation purposes
function transferNFT(address token, uint256 tokenID, uint16 recipientChain, bytes32 recipient) public payable returns (uint64 sequence) { uint16 tokenChain; bytes32 tokenAddress; if (isWrappedAsset(token)) { tokenChain = NFTImplementation(token).chainId(); tokenAddress = NFTImplementation(token).nativeContract(); tokenChain = chainId(); tokenAddress = bytes32(uint256(uint160(token))); require(ERC165(token).supportsInterface(type(IERC721).interfaceId), "must support the ERC721 interface"); require(ERC165(token).supportsInterface(type(IERC721Metadata).interfaceId), "must support the ERC721-Metadata extension"); } string memory symbolString; string memory nameString; string memory uriString; { (,bytes memory queriedSymbol) = token.staticcall(abi.encodeWithSignature("symbol()")); (,bytes memory queriedName) = token.staticcall(abi.encodeWithSignature("name()")); symbolString = abi.decode(queriedSymbol, (string)); nameString = abi.decode(queriedName, (string)); (,bytes memory queriedURI) = token.staticcall(abi.encodeWithSignature("tokenURI(uint256)", tokenID)); uriString = abi.decode(queriedURI, (string)); } bytes32 symbol; bytes32 name; assembly { symbol := mload(add(symbolString, 32)) name := mload(add(nameString, 32)) } IERC721(token).safeTransferFrom(msg.sender, address(this), tokenID); if (tokenChain != chainId()) { NFTImplementation(token).burn(tokenID); } sequence = logTransfer(NFTBridgeStructs.Transfer({ tokenAddress : tokenAddress, tokenChain : tokenChain, name : name, symbol : symbol, tokenID : tokenID, uri : uriString, to : recipient, toChain : recipientChain }), msg.value); emit TransferNFT(sequence, token, tokenID, recipientChain, msg.sender, _truncateAddress(recipient)); }
3,174,124
pragma solidity ^0.4.19; import './libraries/SafeMath.sol'; import './libraries/CryptoDollarStorageProxy.sol'; import './libraries/CryptoFiatStorageProxy.sol'; import './libraries/RewardsStorageProxy.sol'; import './interfaces/ProofTokenInterface.sol'; import './interfaces/RewardsInterface.sol'; import './interfaces/CryptoDollarInterface.sol'; import './interfaces/MedianizerInterface.sol'; import './utils/usingOraclize.sol'; import './utils/Logger.sol'; contract CryptoFiatHub is usingOraclize { using SafeMath for uint256; using CryptoFiatStorageProxy for address; using RewardsStorageProxy for address; enum State { PEGGED, UNPEGGED } enum Feed { ORACLIZE, MEDIANIZER } enum Func { Buy, Sell, SellUnpegged } CryptoDollarInterface public cryptoDollar; ProofTokenInterface public proofToken; RewardsInterface public proofRewards; MedianizerInterface public medianizer; Feed public feed; uint256 pointMultiplier = 10 ** 18; address public store; bool public mockOraclize = true; mapping (bytes32 => address) public callingAddress; mapping (bytes32 => uint256) public callingValue; mapping (bytes32 => Func) public callingFunction; mapping (bytes32 => uint256) public callingFee; string public IPFSHash; event OraclizeCallback(bytes32 queryId); event MedianizerCallback(); event BuyCryptoDollar(bytes32 queryId, address sender, uint256 value, uint256 oraclizeFee); event SellCryptoDollar(bytes32 queryId, address sender, uint256 tokenAmount, uint256 oraclizeFee); event SellUnpeggedCryptoDollar(bytes32 queryId, address sender, uint256 tokenAmount, uint256 oraclizeFee); event BuyCryptoDollarCallback(bytes32 queryId, uint256 exchangeRate, address sender, uint256 tokenAmount, uint256 paymentValue); event SellCryptoDollarCallback(bytes32 queryId, uint256 exchangeRate, address sender, uint256 tokenAmount, uint256 paymentValue); event SellUnpeggedCryptoDollarCallback(bytes32 queryId, uint256 exchangeRate, address sender, uint256 tokenAmount, uint256 paymentValue); function CryptoFiatHub( address _cryptoDollarAddress, address _storeAddress, address _proofTokenAddress, address _proofRewardsAddress) public { cryptoDollar = CryptoDollarInterface(_cryptoDollarAddress); proofToken = ProofTokenInterface(_proofTokenAddress); proofRewards = RewardsInterface(_proofRewardsAddress); store = _storeAddress; } /** * @notice initialize() initialize the CryptoFiat smart contract system (CryptoFiat/CryptoDollar/Rewards) * @param _blocksPerEpoch {uint256} - Number of blocks per reward epoch. * @param _IPFSHash {string} - ETH/USD conversion script IPFS address * @param _medianizerAddress {address} - Medianizer contract address */ //TODO need to set ownership model function initialize(uint256 _blocksPerEpoch, string _IPFSHash, address _medianizerAddress) public { store.setCreationBlockNumber(block.number); store.setBlocksPerEpoch(_blocksPerEpoch); IPFSHash = _IPFSHash; medianizer = MedianizerInterface(_medianizerAddress); } /** * @notice Change the feed type to Oraclize. Oraclize is an provable oracle * infrastructure compatible with Ethereum. */ function useOraclize() public { feed = Feed.ORACLIZE; mockOraclize = false; } /** * @notice Modify the ETH/USD price feed computation script IPFS address * @param _IPFSHash {string} */ function modifyOraclizeIPFSHash(string _IPFSHash) public { IPFSHash = _IPFSHash; } /** * @notice This function sets the Oraclize Address Resolver. * It should only be used for testing with a local ethereum-bridge * @param _oar {address} Oraclize Address Resolver */ function setOraclizeOAR(address _oar) public { if (_oar == 0x0) { _oar = 0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475; } OAR = OraclizeAddrResolverI(_oar); } /** * @notice Change the feed type to Medianizer. The medianizer is a smart-contract * operated by Maker that 'medianizes' the ETH/USD price feed. */ function useMedianizer() public { feed = Feed.MEDIANIZER; } /** * @notice Modify the Medianizer smart-contract address. * @param _medianizerAddress {address} Medianizer smart-contract address */ function modifyMedianizerAddress(address _medianizerAddress) public { medianizer = MedianizerInterface(_medianizerAddress); } /** * @dev Is payable needed ? * @notice Sending ether to the contract will result in an error */ function () public payable { revert(); } /** * @notice Capitalize contract */ function capitalize() public payable {} function buyCryptoDollar() public payable { require(msg.sender != 0x0); require(msg.value > 0); if (feed == Feed.ORACLIZE) { require(this.balance > oraclize_getPrice("computation")); bytes32 queryId; if (!mockOraclize) { queryId = oraclize_query("computation", [IPFSHash], 300000); } else { queryId = keccak256(block.number); //for testing purposes only } callingAddress[queryId] = msg.sender; callingValue[queryId] = msg.value; callingFunction[queryId] = Func.Buy; callingFee[queryId] = oraclize_getPrice("computation"); BuyCryptoDollar(queryId, msg.sender, msg.value, oraclize_getPrice("computation")); } else if (feed == Feed.MEDIANIZER) { bytes32 exchangeRateInBytes; (exchangeRateInBytes, ) = (medianizer.compute()); uint256 exchangeRate = uint256(exchangeRateInBytes); __medianizerCallback(exchangeRate, Func.Buy, msg.sender, msg.value); BuyCryptoDollar(0x0, msg.sender, msg.value, 0); } } /** * @dev Currently the oraclizeFee is withdrawn after receiving the tokens. However, what happens when a user * sells a very small amount of tokens ? Then the contract balance decreases (the total value sent to the user is also 0) * which is problematic. The workarounds are: * - Add a transaction fee that corresponds to the transaction fee * - Put a minimum amount of tokens that you could buy/sell * @notice sellCryptoDollar() sells CryptoDollar tokens for the equivalent USD value at which they were bought * @param _tokenAmount Number of CryptoDollar tokens to be sold against ether */ function sellCryptoDollar(uint256 _tokenAmount) public payable { uint256 oraclizeFee = oraclize_getPrice("computation"); uint256 tokenBalance = cryptoDollar.balanceOf(msg.sender); require(_tokenAmount >= 0); require(_tokenAmount <= tokenBalance); if (feed == Feed.ORACLIZE) { bytes32 queryId; if (!mockOraclize) { queryId = oraclize_query("computation", [IPFSHash], 300000); } else { queryId = keccak256(block.number); //for testing purposes only } callingAddress[queryId] = msg.sender; callingValue[queryId] = _tokenAmount; callingFunction[queryId] = Func.Sell; callingFee[queryId] = oraclizeFee; SellCryptoDollar(queryId, msg.sender, _tokenAmount, oraclizeFee); } else if (feed == Feed.MEDIANIZER) { bytes32 exchangeRateInBytes; (exchangeRateInBytes, ) = (medianizer.compute()); uint256 exchangeRate = uint256(exchangeRateInBytes); __medianizerCallback(exchangeRate, Func.Sell, msg.sender, _tokenAmount); SellCryptoDollar(0x0, msg.sender, _tokenAmount, 0); } } /** * @notice sellUnpeggedCryptoDollar sells CryptoDollar tokens for the equivalent ether value at which they were bought * @param _tokenAmount Number of CryptoDollar tokens to be sold against ether */ function sellUnpeggedCryptoDollar(uint256 _tokenAmount) public payable { uint256 oraclizeFee = oraclize_getPrice("computation"); uint256 tokenBalance = cryptoDollar.balanceOf(msg.sender); require(_tokenAmount >= 0); require(_tokenAmount <= tokenBalance); if (feed == Feed.ORACLIZE) { bytes32 queryId; if (!mockOraclize) { queryId = oraclize_query("computation", [IPFSHash], 300000); } else { queryId = keccak256(block.number); } callingAddress[queryId] = msg.sender; callingValue[queryId] = _tokenAmount; callingFunction[queryId] = Func.SellUnpegged; callingFee[queryId] = oraclizeFee; SellUnpeggedCryptoDollar(queryId, msg.sender, _tokenAmount, oraclizeFee); } else if (feed == Feed.MEDIANIZER) { bytes32 exchangeRateInBytes; (exchangeRateInBytes, ) = (medianizer.compute()); uint256 exchangeRate = uint256(exchangeRateInBytes); __medianizerCallback(exchangeRate, Func.SellUnpegged, msg.sender, _tokenAmount); SellUnpeggedCryptoDollar(0x0, msg.sender, _tokenAmount, 0); } } /** * @notice __callback is triggered asynchronously after a buy/sell through Oraclize. * @dev In production this function should be callable only by the oraclize callback address. * The contract has to be appropriately set up to do so * @param _queryId {bytes32} Oraclize Query ID identidying the original transaction * @param _result {string} Oraclize query result (average of the ETH/USD price) */ function __callback(bytes32 _queryId, string _result) public onlyOraclize { uint256 exchangeRate = parseInt(_result); uint256 value = callingValue[_queryId]; address sender = callingAddress[_queryId]; uint256 fee = callingFee[_queryId]; if (callingFunction[_queryId] == Func.Buy) { buyCryptoDollarCallback(_queryId, exchangeRate, value, sender, fee); } else if (callingFunction[_queryId] == Func.Sell) { sellCryptoDollarCallback(_queryId, exchangeRate, value, sender, fee); } else if (callingFunction[_queryId] == Func.SellUnpegged) { sellUnpeggedCryptoDollarCallback(_queryId, exchangeRate, value, sender, fee); } } function __medianizerCallback(uint256 _exchangeRate, Func _func, address _sender, uint256 _value) internal { if (_func == Func.Buy) { buyCryptoDollarCallback(0x0, _exchangeRate, _value, _sender, 0); } else if (_func == Func.Sell) { sellCryptoDollarCallback(0x0, _exchangeRate, _value, _sender, 0); } else if (_func == Func.SellUnpegged) { sellUnpeggedCryptoDollarCallback(0x0, _exchangeRate, _value, _sender, 0); } } /** * @notice buyCryptoDollarCallback is called internally through __callback * This function is called if the queryID corresponds to a Buy call * @param _exchangeRate {uint256} Oraclize queryID identifying the original transaction * @param _value {uint256} Amount of ether exchanged for cryptodollar tokens * @param _sender {address} Transaction sender address * @param _oraclizeFee {uint256} Oraclize Fee */ function buyCryptoDollarCallback(bytes32 _queryId, uint256 _exchangeRate, uint256 _value, address _sender, uint256 _oraclizeFee) internal { require(inState(State.PEGGED, _exchangeRate)); uint256 tokenHoldersFee = _value.div(200); uint256 bufferFee = _value.div(200); uint256 paymentValue = _value - tokenHoldersFee - bufferFee - _oraclizeFee; proofRewards.receiveRewards.value(tokenHoldersFee)(); uint256 tokenAmount = paymentValue.mul(_exchangeRate).div(1 ether); cryptoDollar.buy(_sender, tokenAmount, paymentValue); BuyCryptoDollarCallback(_queryId, _exchangeRate, _sender, tokenAmount, paymentValue); } /** * @notice buyCryptoDollarCallback is called internally through __callback * This function is called if the queryID corresponds to a Sell call * @param _exchangeRate {uint256} Exchange Rate * @param _tokenAmount {uint256} Amount of tokens to be sold * @param _sender {address} Transaction sender address * @param _oraclizeFee {string} Oraclize Fee (0 if called from medianizer) */ function sellCryptoDollarCallback(bytes32 _queryId, uint256 _exchangeRate, uint256 _tokenAmount, address _sender, uint256 _oraclizeFee) internal { require(inState(State.PEGGED, _exchangeRate)); uint256 tokenBalance = cryptoDollar.balanceOf(_sender); uint256 reservedEther = cryptoDollar.reservedEther(_sender); require(_tokenAmount > 0); require(_tokenAmount <= tokenBalance); uint256 tokenValue = _tokenAmount.mul(1 ether).div(_exchangeRate); require(tokenValue > _oraclizeFee); uint256 paymentValue = tokenValue - _oraclizeFee; uint256 etherValue = _tokenAmount.mul(reservedEther).div(tokenBalance); cryptoDollar.sell(_sender, _tokenAmount, etherValue); _sender.transfer(paymentValue); SellCryptoDollarCallback(_queryId, _exchangeRate, _sender, _tokenAmount, paymentValue); } /** * @notice sellUnpeggedCryptoDollarCallback is called internally through __callback * This function is called if the queryID corresponds to a SellUnpegged call * @param _exchangeRate {uint256} Exchange rate * @param _tokenAmount {uint256} Amount of tokens to be sold for ether * @param _sender {address} Transaction sender address * @param _oraclizeFee {string} Oraclize Fee (0 if called from medianizer) */ function sellUnpeggedCryptoDollarCallback(bytes32 _queryId, uint256 _exchangeRate, uint256 _tokenAmount, address _sender, uint256 _oraclizeFee) internal { require(inState(State.UNPEGGED, _exchangeRate)); uint256 tokenBalance = cryptoDollar.balanceOf(_sender); uint256 reservedEther = cryptoDollar.reservedEther(_sender); require(_tokenAmount > 0); require(_tokenAmount <= tokenBalance); uint256 tokenValue = _tokenAmount.mul(reservedEther).div(tokenBalance); require(tokenValue > _oraclizeFee); uint256 paymentValue = tokenValue - _oraclizeFee; cryptoDollar.sell(_sender, _tokenAmount, tokenValue); _sender.transfer(paymentValue); SellUnpeggedCryptoDollarCallback(_queryId, _exchangeRate, _sender, _tokenAmount, paymentValue); } /** * @notice Proxies _holder CryptoDollar token balance from the CryptoDollar contract * @param _holder cryptoDollar token holder balance * @return the cryptoDollar token balance of _holder */ function cryptoDollarBalance(address _holder) public constant returns(uint256) { return cryptoDollar.balanceOf(_holder); } /** * @notice Proxies the total supply of CryptoDollar tokens from the CryptoDollar contract * @return Total supply of cryptoDollar */ function cryptoDollarTotalSupply() public constant returns (uint256) { return cryptoDollar.totalSupply(); } /** * @notice The totalOutstanding() function returns the amount of ether that is owed to all cryptoDollar token holders for a pegged contract state * @return Total value in ether of the cryptoDollar tokens that have been issued */ function totalOutstanding(uint256 _exchangeRate) public constant returns(uint256) { uint256 supply = cryptoDollar.totalSupply(); return supply.mul(1 ether).div(_exchangeRate); } /** * @notice The buffer function computes the difference between the current contract balance and the amount of outstanding tokens. * @param _exchangeRate {uint256} * @return {int256} Buffer Value */ function buffer(uint256 _exchangeRate) public constant returns (int256) { int256 value = int256(this.balance - totalOutstanding(_exchangeRate)); return value; } /** * @notice Returns a boolean corresponding to whether the contract is in state _state * (for 1 ETH = _exchangeRate USD) * @param _state {State} * @param _exchangeRate {uint256} * @return {bool} */ function inState(State _state, uint256 _exchangeRate) public view returns (bool) { if (buffer(_exchangeRate) > 0) { return (_state == State.PEGGED); } else { return (_state == State.UNPEGGED); } } /** * @notice Returns contract balance * @return {uint256} Contract Balance */ function contractBalance() public constant returns (uint256) { return this.balance; } /** * @notice Allows cryptoDollar buyers to withdraw the ether value sent to the contract * before the callback function happens. This allows users to retrieve the funds sent * to the CryptoDollar contract in case oraclize fails to send a callback transaction * @param _queryId {bytes32} - Oraclize query ID */ function withdrawEther(bytes32 _queryId) public { require(callingAddress[_queryId] == msg.sender); require(callingFunction[_queryId] == Func.Buy); uint256 oraclizeFee = callingFee[_queryId]; uint256 value = callingValue[_queryId]; uint256 tokenHoldersFee = value.div(200); uint256 paymentValue = value - tokenHoldersFee - oraclizeFee; require(paymentValue > 0); delete callingValue[_queryId]; msg.sender.transfer(paymentValue); } modifier onlyOraclize() { if (!mockOraclize) { require(msg.sender == oraclize_cbAddress()); } _; } }
Change the feed type to Medianizer. The medianizer is a smart-contract operated by Maker that 'medianizes' the ETH/USD price feed./
function useMedianizer() public { feed = Feed.MEDIANIZER; }
6,385,751
// SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./WSSLPUserProxy.sol"; import "../../helpers/ReentrancyGuard.sol"; import "../../helpers/TransferHelper.sol"; import "../../Auth2.sol"; import "../../interfaces/IVault.sol"; import "../../interfaces/IERC20WithOptional.sol"; import "../../interfaces/wrapped-assets/IWrappedAsset.sol"; import "../../interfaces/wrapped-assets/ITopDog.sol"; import "../../interfaces/wrapped-assets/ISushiSwapLpToken.sol"; /** * @title ShibaSwapWrappedLp **/ contract WrappedShibaSwapLp is IWrappedAsset, Auth2, ERC20, ReentrancyGuard { using SafeMath for uint256; bytes32 public constant override isUnitProtocolWrappedAsset = keccak256("UnitProtocolWrappedAsset"); IVault public immutable vault; ITopDog public immutable topDog; uint256 public immutable topDogPoolId; IERC20 public immutable boneToken; address public immutable userProxyImplementation; mapping(address => WSSLPUserProxy) public usersProxies; mapping (address => mapping (bytes4 => bool)) allowedBoneLockersSelectors; address public feeReceiver; uint8 public feePercent = 10; constructor( address _vaultParameters, ITopDog _topDog, uint256 _topDogPoolId, address _feeReceiver ) Auth2(_vaultParameters) ERC20( string( abi.encodePacked( "Wrapped by Unit ", getSsLpTokenName(_topDog, _topDogPoolId), " ", getSsLpTokenToken0Symbol(_topDog, _topDogPoolId), "-", getSsLpTokenToken1Symbol(_topDog, _topDogPoolId) ) ), string( abi.encodePacked( "wu", getSsLpTokenSymbol(_topDog, _topDogPoolId), getSsLpTokenToken0Symbol(_topDog, _topDogPoolId), getSsLpTokenToken1Symbol(_topDog, _topDogPoolId) ) ) ) { boneToken = _topDog.bone(); topDog = _topDog; topDogPoolId = _topDogPoolId; vault = IVault(VaultParameters(_vaultParameters).vault()); _setupDecimals(IERC20WithOptional(getSsLpToken(_topDog, _topDogPoolId)).decimals()); feeReceiver = _feeReceiver; userProxyImplementation = address(new WSSLPUserProxy(_topDog, _topDogPoolId)); } function setFeeReceiver(address _feeReceiver) public onlyManager { feeReceiver = _feeReceiver; emit FeeReceiverChanged(_feeReceiver); } function setFee(uint8 _feePercent) public onlyManager { require(_feePercent <= 50, "Unit Protocol Wrapped Assets: INVALID_FEE"); feePercent = _feePercent; emit FeeChanged(_feePercent); } /** * @dev in case of change bone locker to unsupported by current methods one */ function setAllowedBoneLockerSelector(address _boneLocker, bytes4 _selector, bool _isAllowed) public onlyManager { allowedBoneLockersSelectors[_boneLocker][_selector] = _isAllowed; if (_isAllowed) { emit AllowedBoneLockerSelectorAdded(_boneLocker, _selector); } else { emit AllowedBoneLockerSelectorRemoved(_boneLocker, _selector); } } /** * @notice Approve sslp token to spend from user proxy (in case of change sslp) */ function approveSslpToTopDog() public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); IERC20 sslpToken = getUnderlyingToken(); userProxy.approveSslpToTopDog(sslpToken); } /** * @notice Get tokens from user, send them to TopDog, sent to user wrapped tokens * @dev only user or CDPManager could call this method */ function deposit(address _user, uint256 _amount) public override nonReentrant { require(_amount > 0, "Unit Protocol Wrapped Assets: INVALID_AMOUNT"); require(msg.sender == _user || vaultParameters.canModifyVault(msg.sender), "Unit Protocol Wrapped Assets: AUTH_FAILED"); IERC20 sslpToken = getUnderlyingToken(); WSSLPUserProxy userProxy = _getOrCreateUserProxy(_user, sslpToken); // get tokens from user, need approve of sslp tokens to pool TransferHelper.safeTransferFrom(address(sslpToken), _user, address(userProxy), _amount); // deposit them to TopDog userProxy.deposit(_amount); // wrapped tokens to user _mint(_user, _amount); emit Deposit(_user, _amount); } /** * @notice Unwrap tokens, withdraw from TopDog and send them to user * @dev only user or CDPManager could call this method */ function withdraw(address _user, uint256 _amount) public override nonReentrant { require(_amount > 0, "Unit Protocol Wrapped Assets: INVALID_AMOUNT"); require(msg.sender == _user || vaultParameters.canModifyVault(msg.sender), "Unit Protocol Wrapped Assets: AUTH_FAILED"); IERC20 sslpToken = getUnderlyingToken(); WSSLPUserProxy userProxy = _requireUserProxy(_user); // get wrapped tokens from user _burn(_user, _amount); // withdraw funds from TopDog userProxy.withdraw(sslpToken, _amount, _user); emit Withdraw(_user, _amount); } /** * @notice Manually move position (or its part) to another user (for example in case of liquidation) * @dev Important! Use only with additional token transferring outside this function (example: liquidation - tokens are in vault and transferred by vault) * @dev only CDPManager could call this method */ function movePosition(address _userFrom, address _userTo, uint256 _amount) public override nonReentrant hasVaultAccess { require(_userFrom != address(vault) && _userTo != address(vault), "Unit Protocol Wrapped Assets: NOT_ALLOWED_FOR_VAULT"); if (_userFrom == _userTo || _amount == 0) { return; } IERC20 sslpToken = getUnderlyingToken(); WSSLPUserProxy userFromProxy = _requireUserProxy(_userFrom); WSSLPUserProxy userToProxy = _getOrCreateUserProxy(_userTo, sslpToken); userFromProxy.withdraw(sslpToken, _amount, address(userToProxy)); userToProxy.deposit(_amount); emit Withdraw(_userFrom, _amount); emit Deposit(_userTo, _amount); emit PositionMoved(_userFrom, _userTo, _amount); } /** * @notice Calculates pending reward for user. Not taken into account unclaimed reward from BoneLockers. * @notice Use getClaimableRewardFromBoneLocker to calculate unclaimed reward from BoneLockers */ function pendingReward(address _user) public override view returns (uint256) { WSSLPUserProxy userProxy = usersProxies[_user]; if (address(userProxy) == address(0)) { return 0; } return userProxy.pendingReward(feeReceiver, feePercent); } /** * @notice Claim pending direct reward for user. * @notice Use claimRewardFromBoneLockers claim reward from BoneLockers */ function claimReward(address _user) public override nonReentrant { require(_user == msg.sender, "Unit Protocol Wrapped Assets: AUTH_FAILED"); WSSLPUserProxy userProxy = _requireUserProxy(_user); userProxy.claimReward(_user, feeReceiver, feePercent); } /** * @notice Get claimable amount from BoneLocker * @param _user user address * @param _boneLocker BoneLocker to check, pass zero address to check current */ function getClaimableRewardFromBoneLocker(address _user, IBoneLocker _boneLocker) public view returns (uint256) { WSSLPUserProxy userProxy = usersProxies[_user]; if (address(userProxy) == address(0)) { return 0; } return userProxy.getClaimableRewardFromBoneLocker(_boneLocker, feeReceiver, feePercent); } /** * @notice Claim bones from BoneLockers * @notice Since it could be a lot of pending rewards items parameters are used limit tx size * @param _boneLocker BoneLocker to claim, pass zero address to claim from current * @param _maxBoneLockerRewardsAtOneClaim max amount of rewards items to claim from BoneLocker, pass 0 to claim all rewards */ function claimRewardFromBoneLocker(IBoneLocker _boneLocker, uint256 _maxBoneLockerRewardsAtOneClaim) public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); userProxy.claimRewardFromBoneLocker(msg.sender, _boneLocker, _maxBoneLockerRewardsAtOneClaim, feeReceiver, feePercent); } /** * @notice get SSLP token * @dev not immutable since it could be changed in TopDog */ function getUnderlyingToken() public override view returns (IERC20) { (IERC20 _sslpToken,,,) = topDog.poolInfo(topDogPoolId); return _sslpToken; } /** * @notice Withdraw tokens from topdog to user proxy without caring about rewards. EMERGENCY ONLY. * @notice To withdraw tokens from user proxy to user use `withdrawToken` */ function emergencyWithdraw() public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); uint amount = userProxy.getDepositedAmount(); _burn(msg.sender, amount); assert(balanceOf(msg.sender) == 0); userProxy.emergencyWithdraw(); emit EmergencyWithdraw(msg.sender, amount); } function withdrawToken(address _token, uint _amount) public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); userProxy.withdrawToken(_token, msg.sender, _amount, feeReceiver, feePercent); emit TokenWithdraw(msg.sender, _token, _amount); } function readBoneLocker(address _user, address _boneLocker, bytes calldata _callData) public view returns (bool success, bytes memory data) { WSSLPUserProxy userProxy = _requireUserProxy(_user); (success, data) = userProxy.readBoneLocker(_boneLocker, _callData); } function callBoneLocker(address _boneLocker, bytes calldata _callData) public nonReentrant returns (bool success, bytes memory data) { bytes4 selector; assembly { selector := calldataload(_callData.offset) } require(allowedBoneLockersSelectors[_boneLocker][selector], "Unit Protocol Wrapped Assets: UNSUPPORTED_SELECTOR"); WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); (success, data) = userProxy.callBoneLocker(_boneLocker, _callData); } /** * @dev Get sslp token for using in constructor */ function getSsLpToken(ITopDog _topDog, uint256 _topDogPoolId) private view returns (address) { (IERC20 _sslpToken,,,) = _topDog.poolInfo(_topDogPoolId); return address(_sslpToken); } /** * @dev Get symbol of sslp token for using in constructor */ function getSsLpTokenSymbol(ITopDog _topDog, uint256 _topDogPoolId) private view returns (string memory) { return IERC20WithOptional(getSsLpToken(_topDog, _topDogPoolId)).symbol(); } /** * @dev Get name of sslp token for using in constructor */ function getSsLpTokenName(ITopDog _topDog, uint256 _topDogPoolId) private view returns (string memory) { return IERC20WithOptional(getSsLpToken(_topDog, _topDogPoolId)).name(); } /** * @dev Get token0 symbol of sslp token for using in constructor */ function getSsLpTokenToken0Symbol(ITopDog _topDog, uint256 _topDogPoolId) private view returns (string memory) { return IERC20WithOptional(address(ISushiSwapLpToken(getSsLpToken(_topDog, _topDogPoolId)).token0())).symbol(); } /** * @dev Get token1 symbol of sslp token for using in constructor */ function getSsLpTokenToken1Symbol(ITopDog _topDog, uint256 _topDogPoolId) private view returns (string memory) { return IERC20WithOptional(address(ISushiSwapLpToken(getSsLpToken(_topDog, _topDogPoolId)).token1())).symbol(); } /** * @dev No direct transfers between users allowed since we store positions info in userInfo. */ function _transfer(address sender, address recipient, uint256 amount) internal override onlyVault { require(sender == address(vault) || recipient == address(vault), "Unit Protocol Wrapped Assets: AUTH_FAILED"); super._transfer(sender, recipient, amount); } function _requireUserProxy(address _user) internal view returns (WSSLPUserProxy userProxy) { userProxy = usersProxies[_user]; require(address(userProxy) != address(0), "Unit Protocol Wrapped Assets: NO_DEPOSIT"); } function _getOrCreateUserProxy(address _user, IERC20 sslpToken) internal returns (WSSLPUserProxy userProxy) { userProxy = usersProxies[_user]; if (address(userProxy) == address(0)) { // create new userProxy = WSSLPUserProxy(createClone(userProxyImplementation)); userProxy.approveSslpToTopDog(sslpToken); usersProxies[_user] = userProxy; } } /** * @dev see https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol */ function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2022 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; // have to use OZ safemath since it is used in WSSLP import "../../interfaces/wrapped-assets/ITopDog.sol"; import "../../helpers/TransferHelper.sol"; /** * @title WSSLPUserProxy **/ contract WSSLPUserProxy { using SafeMath for uint256; address public immutable manager; ITopDog public immutable topDog; uint256 public immutable topDogPoolId; IERC20 public immutable boneToken; modifier onlyManager() { require(msg.sender == manager, "Unit Protocol Wrapped Assets: AUTH_FAILED"); _; } constructor(ITopDog _topDog, uint256 _topDogPoolId) { manager = msg.sender; topDog = _topDog; topDogPoolId = _topDogPoolId; boneToken = _topDog.bone(); } /** * @dev in case of change sslp */ function approveSslpToTopDog(IERC20 _sslpToken) public onlyManager { TransferHelper.safeApprove(address(_sslpToken), address(topDog), type(uint256).max); } function deposit(uint256 _amount) public onlyManager { topDog.deposit(topDogPoolId, _amount); } function withdraw(IERC20 _sslpToken, uint256 _amount, address _sentTokensTo) public onlyManager { topDog.withdraw(topDogPoolId, _amount); TransferHelper.safeTransfer(address(_sslpToken), _sentTokensTo, _amount); } function pendingReward(address _feeReceiver, uint8 _feePercent) public view returns (uint) { uint balance = boneToken.balanceOf(address(this)); uint pending = topDog.pendingBone(topDogPoolId, address(this)).mul(topDog.rewardMintPercent()).div(100); (uint amountWithoutFee, ) = _calcFee(balance.add(pending), _feeReceiver, _feePercent); return amountWithoutFee; } function claimReward(address _user, address _feeReceiver, uint8 _feePercent) public onlyManager { topDog.deposit(topDogPoolId, 0); // get current reward (no separate methods) _sendAllBonesToUser(_user, _feeReceiver, _feePercent); } function _calcFee(uint _amount, address _feeReceiver, uint8 _feePercent) internal pure returns (uint amountWithoutFee, uint fee) { if (_feePercent == 0 || _feeReceiver == address(0)) { return (_amount, 0); } fee = _amount.mul(_feePercent).div(100); return (_amount.sub(fee), fee); } function _sendAllBonesToUser(address _user, address _feeReceiver, uint8 _feePercent) internal { uint balance = boneToken.balanceOf(address(this)); _sendBonesToUser(_user, balance, _feeReceiver, _feePercent); } function _sendBonesToUser(address _user, uint _amount, address _feeReceiver, uint8 _feePercent) internal { (uint amountWithoutFee, uint fee) = _calcFee(_amount, _feeReceiver, _feePercent); if (fee > 0) { TransferHelper.safeTransfer(address(boneToken), _feeReceiver, fee); } TransferHelper.safeTransfer(address(boneToken), _user, amountWithoutFee); } function getClaimableRewardFromBoneLocker(IBoneLocker _boneLocker, address _feeReceiver, uint8 _feePercent) public view returns (uint) { if (address(_boneLocker) == address(0)) { _boneLocker = topDog.boneLocker(); } (uint amountWithoutFee, ) = _calcFee(_boneLocker.getClaimableAmount(address(this)), _feeReceiver, _feePercent); return amountWithoutFee; } function claimRewardFromBoneLocker(address _user, IBoneLocker _boneLocker, uint256 _maxBoneLockerRewardsAtOneClaim, address _feeReceiver, uint8 _feePercent) public onlyManager { if (address(_boneLocker) == address(0)) { _boneLocker = topDog.boneLocker(); } (uint256 left, uint256 right) = _boneLocker.getLeftRightCounters(address(this)); if (right <= left) { return; } if (_maxBoneLockerRewardsAtOneClaim > 0 && right - left > _maxBoneLockerRewardsAtOneClaim) { right = left + _maxBoneLockerRewardsAtOneClaim; } _boneLocker.claimAll(right); _sendAllBonesToUser(_user, _feeReceiver, _feePercent); } function emergencyWithdraw() public onlyManager { topDog.emergencyWithdraw(topDogPoolId); } function withdrawToken(address _token, address _user, uint _amount, address _feeReceiver, uint8 _feePercent) public onlyManager { if (_token == address(boneToken)) { _sendBonesToUser(_user, _amount, _feeReceiver, _feePercent); } else { TransferHelper.safeTransfer(_token, _user, _amount); } } function readBoneLocker(address _boneLocker, bytes calldata _callData) public view returns (bool success, bytes memory data) { (success, data) = _boneLocker.staticcall(_callData); } function callBoneLocker(address _boneLocker, bytes calldata _callData) public onlyManager returns (bool success, bytes memory data) { (success, data) = _boneLocker.call(_callData); } function getDepositedAmount() public view returns (uint amount) { (amount, ) = topDog.userInfo(topDogPoolId, address (this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0-or-later /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "./VaultParameters.sol"; /** * @title Auth2 * @dev Manages USDP's system access * @dev copy of Auth from VaultParameters.sol but with immutable vaultParameters for saving gas **/ contract Auth2 { // address of the the contract with vault parameters VaultParameters public immutable vaultParameters; constructor(address _parameters) { require(_parameters != address(0), "Unit Protocol: ZERO_ADDRESS"); vaultParameters = VaultParameters(_parameters); } // ensures tx's sender is a manager modifier onlyManager() { require(vaultParameters.isManager(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is able to modify the Vault modifier hasVaultAccess() { require(vaultParameters.canModifyVault(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is the Vault modifier onlyVault() { require(msg.sender == vaultParameters.vault(), "Unit Protocol: AUTH_FAILED"); _; } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVault { function DENOMINATOR_1E2 ( ) external view returns ( uint256 ); function DENOMINATOR_1E5 ( ) external view returns ( uint256 ); function borrow ( address asset, address user, uint256 amount ) external returns ( uint256 ); function calculateFee ( address asset, address user, uint256 amount ) external view returns ( uint256 ); function changeOracleType ( address asset, address user, uint256 newOracleType ) external; function chargeFee ( address asset, address user, uint256 amount ) external; function col ( ) external view returns ( address ); function colToken ( address, address ) external view returns ( uint256 ); function collaterals ( address, address ) external view returns ( uint256 ); function debts ( address, address ) external view returns ( uint256 ); function depositCol ( address asset, address user, uint256 amount ) external; function depositEth ( address user ) external payable; function depositMain ( address asset, address user, uint256 amount ) external; function destroy ( address asset, address user ) external; function getTotalDebt ( address asset, address user ) external view returns ( uint256 ); function lastUpdate ( address, address ) external view returns ( uint256 ); function liquidate ( address asset, address positionOwner, uint256 mainAssetToLiquidator, uint256 colToLiquidator, uint256 mainAssetToPositionOwner, uint256 colToPositionOwner, uint256 repayment, uint256 penalty, address liquidator ) external; function liquidationBlock ( address, address ) external view returns ( uint256 ); function liquidationFee ( address, address ) external view returns ( uint256 ); function liquidationPrice ( address, address ) external view returns ( uint256 ); function oracleType ( address, address ) external view returns ( uint256 ); function repay ( address asset, address user, uint256 amount ) external returns ( uint256 ); function spawn ( address asset, address user, uint256 _oracleType ) external; function stabilityFee ( address, address ) external view returns ( uint256 ); function tokenDebts ( address ) external view returns ( uint256 ); function triggerLiquidation ( address asset, address positionOwner, uint256 initialPrice ) external; function update ( address asset, address user ) external; function usdp ( ) external view returns ( address ); function vaultParameters ( ) external view returns ( address ); function weth ( ) external view returns ( address payable ); function withdrawCol ( address asset, address user, uint256 amount ) external; function withdrawEth ( address user, uint256 amount ) external; function withdrawMain ( address asset, address user, uint256 amount ) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20WithOptional is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWrappedAsset is IERC20 /* IERC20WithOptional */ { event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event PositionMoved(address indexed userFrom, address indexed userTo, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event TokenWithdraw(address indexed user, address token, uint256 amount); event FeeChanged(uint256 newFeePercent); event FeeReceiverChanged(address newFeeReceiver); event AllowedBoneLockerSelectorAdded(address boneLocker, bytes4 selector); event AllowedBoneLockerSelectorRemoved(address boneLocker, bytes4 selector); /** * @notice Get underlying token */ function getUnderlyingToken() external view returns (IERC20); /** * @notice deposit underlying token and send wrapped token to user * @dev Important! Only user or trusted contracts must be able to call this method */ function deposit(address _userAddr, uint256 _amount) external; /** * @notice get wrapped token and return underlying * @dev Important! Only user or trusted contracts must be able to call this method */ function withdraw(address _userAddr, uint256 _amount) external; /** * @notice get pending reward amount for user if reward is supported */ function pendingReward(address _userAddr) external view returns (uint256); /** * @notice claim pending reward for user if reward is supported */ function claimReward(address _userAddr) external; /** * @notice Manually move position (or its part) to another user (for example in case of liquidation) * @dev Important! Only trusted contracts must be able to call this method */ function movePosition(address _userAddrFrom, address _userAddrTo, uint256 _amount) external; /** * @dev function for checks that asset is unitprotocol wrapped asset. * @dev For wrapped assets must return keccak256("UnitProtocolWrappedAsset") */ function isUnitProtocolWrappedAsset() external view returns (bytes32); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IBoneLocker.sol"; import "./IBoneToken.sol"; /** * See https://etherscan.io/address/0x94235659cf8b805b2c658f9ea2d6d6ddbb17c8d7#code */ interface ITopDog { function bone() external view returns (IBoneToken); function boneLocker() external view returns (IBoneLocker); function poolInfo(uint256) external view returns (IERC20, uint256, uint256, uint256); function poolLength() external view returns (uint256); function userInfo(uint256, address) external view returns (uint256, uint256); function rewardMintPercent() external view returns (uint256); function pendingBone(uint256 _pid, address _user) external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ISushiSwapLpToken is IERC20 /* IERC20WithOptional */ { function token0() external view returns (address); function token1() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; /** * @dev BoneToken locker contract interface */ interface IBoneLocker { function lockInfoByUser(address, uint256) external view returns (uint256, uint256, bool); function lockingPeriod() external view returns (uint256); // function to claim all the tokens locked for a user, after the locking period function claimAllForUser(uint256 r, address user) external; // function to claim all the tokens locked by user, after the locking period function claimAll(uint256 r) external; // function to get claimable amount for any user function getClaimableAmount(address _user) external view returns(uint256); // get the left and right headers for a user, left header is the index counter till which we have already iterated, right header is basically the length of user's lockInfo array function getLeftRightCounters(address _user) external view returns(uint256, uint256); function lock(address _holder, uint256 _amount, bool _isDev) external; function setLockingPeriod(uint256 _newLockingPeriod, uint256 _newDevLockingPeriod) external; function emergencyWithdrawOwner(address _to) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IBoneToken is IERC20 { function mint(address _to, uint256 _amount) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; /** * @title Auth * @dev Manages USDP's system access **/ contract Auth { // address of the the contract with vault parameters VaultParameters public vaultParameters; constructor(address _parameters) { vaultParameters = VaultParameters(_parameters); } // ensures tx's sender is a manager modifier onlyManager() { require(vaultParameters.isManager(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is able to modify the Vault modifier hasVaultAccess() { require(vaultParameters.canModifyVault(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is the Vault modifier onlyVault() { require(msg.sender == vaultParameters.vault(), "Unit Protocol: AUTH_FAILED"); _; } } /** * @title VaultParameters **/ contract VaultParameters is Auth { // map token to stability fee percentage; 3 decimals mapping(address => uint) public stabilityFee; // map token to liquidation fee percentage, 0 decimals mapping(address => uint) public liquidationFee; // map token to USDP mint limit mapping(address => uint) public tokenDebtLimit; // permissions to modify the Vault mapping(address => bool) public canModifyVault; // managers mapping(address => bool) public isManager; // enabled oracle types mapping(uint => mapping (address => bool)) public isOracleTypeEnabled; // address of the Vault address payable public vault; // The foundation address address public foundation; /** * The address for an Ethereum contract is deterministically computed from the address of its creator (sender) * and how many transactions the creator has sent (nonce). The sender and nonce are RLP encoded and then * hashed with Keccak-256. * Therefore, the Vault address can be pre-computed and passed as an argument before deployment. **/ constructor(address payable _vault, address _foundation) Auth(address(this)) { require(_vault != address(0), "Unit Protocol: ZERO_ADDRESS"); require(_foundation != address(0), "Unit Protocol: ZERO_ADDRESS"); isManager[msg.sender] = true; vault = _vault; foundation = _foundation; } /** * @notice Only manager is able to call this function * @dev Grants and revokes manager's status of any address * @param who The target address * @param permit The permission flag **/ function setManager(address who, bool permit) external onlyManager { isManager[who] = permit; } /** * @notice Only manager is able to call this function * @dev Sets the foundation address * @param newFoundation The new foundation address **/ function setFoundation(address newFoundation) external onlyManager { require(newFoundation != address(0), "Unit Protocol: ZERO_ADDRESS"); foundation = newFoundation; } /** * @notice Only manager is able to call this function * @dev Sets ability to use token as the main collateral * @param asset The address of the main collateral token * @param stabilityFeeValue The percentage of the year stability fee (3 decimals) * @param liquidationFeeValue The liquidation fee percentage (0 decimals) * @param usdpLimit The USDP token issue limit * @param oracles The enables oracle types **/ function setCollateral( address asset, uint stabilityFeeValue, uint liquidationFeeValue, uint usdpLimit, uint[] calldata oracles ) external onlyManager { setStabilityFee(asset, stabilityFeeValue); setLiquidationFee(asset, liquidationFeeValue); setTokenDebtLimit(asset, usdpLimit); for (uint i=0; i < oracles.length; i++) { setOracleType(oracles[i], asset, true); } } /** * @notice Only manager is able to call this function * @dev Sets a permission for an address to modify the Vault * @param who The target address * @param permit The permission flag **/ function setVaultAccess(address who, bool permit) external onlyManager { canModifyVault[who] = permit; } /** * @notice Only manager is able to call this function * @dev Sets the percentage of the year stability fee for a particular collateral * @param asset The address of the main collateral token * @param newValue The stability fee percentage (3 decimals) **/ function setStabilityFee(address asset, uint newValue) public onlyManager { stabilityFee[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the percentage of the liquidation fee for a particular collateral * @param asset The address of the main collateral token * @param newValue The liquidation fee percentage (0 decimals) **/ function setLiquidationFee(address asset, uint newValue) public onlyManager { require(newValue <= 100, "Unit Protocol: VALUE_OUT_OF_RANGE"); liquidationFee[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Enables/disables oracle types * @param _type The type of the oracle * @param asset The address of the main collateral token * @param enabled The control flag **/ function setOracleType(uint _type, address asset, bool enabled) public onlyManager { isOracleTypeEnabled[_type][asset] = enabled; } /** * @notice Only manager is able to call this function * @dev Sets USDP limit for a specific collateral * @param asset The address of the main collateral token * @param limit The limit number **/ function setTokenDebtLimit(address asset, uint limit) public onlyManager { tokenDebtLimit[asset] = limit; } }
Claim bones from BoneLockers Since it could be a lot of pending rewards items parameters are used limit tx size _boneLocker BoneLocker to claim, pass zero address to claim from current _maxBoneLockerRewardsAtOneClaim max amount of rewards items to claim from BoneLocker, pass 0 to claim all rewards/
function claimRewardFromBoneLocker(IBoneLocker _boneLocker, uint256 _maxBoneLockerRewardsAtOneClaim) public nonReentrant { WSSLPUserProxy userProxy = _requireUserProxy(msg.sender); userProxy.claimRewardFromBoneLocker(msg.sender, _boneLocker, _maxBoneLockerRewardsAtOneClaim, feeReceiver, feePercent); }
1,248,809
pragma solidity ^0.5.0; import "./DappToken.sol"; import "./DaiToken.sol"; contract TokenFarm { string public name = "Dapp Token Farm"; address public owner; DappToken public dappToken; DaiToken public daiToken; address[] public stakers; mapping(address => uint) public stakingBalance; mapping(address => bool) public hasStaked; mapping(address => bool) public isStaking; constructor(DappToken _dappToken, DaiToken _daiToken) public { dappToken = _dappToken; daiToken = _daiToken; owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "caller must be the owner"); _; } /* Stakes Tokens (Deposit): An investor will deposit the DAI into the smart contracts to starting earning rewards. Core Thing: Transfer the DAI tokens from the investor's wallet to this smart contract. */ function stakeTokens(uint _amount) public { // transfer Mock DAI tokens to this contract for staking daiToken.transferFrom(msg.sender, address(this), _amount); // update staking balance stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount; // add user to stakers array *only* if they haven't staked already if(!hasStaked[msg.sender]) { stakers.push(msg.sender); } // update stakng status isStaking[msg.sender] = true; hasStaked[msg.sender] = true; } // Unstaking Tokens (Withdraw): Withdraw money from DApp. function unstakeTokens() public { // fetch staking balance uint balance = stakingBalance[msg.sender]; // require amount greter than 0 require(balance > 0, "staking balance cannot be 0"); // transfer Mock Dai tokens to this contract for staking daiToken.transfer(msg.sender, balance); // reset staking balance stakingBalance[msg.sender] = 0; // update staking status isStaking[msg.sender] = false; } /* Issuing Tokens: Earning interest which is issuing tokens for people who stake them. Core Thing: Distribute DApp tokens as interest and also allow the investor to unstake their tokens from the app so give them interest using the app. */ function issueTokens() public onlyOwner { // issue tokens to all stakers for (uint i=0; i<stakers.length; i++) { address recipient = stakers[i]; uint balance = stakingBalance[recipient]; if(balance > 0) { dappToken.transfer(recipient, balance); } } } }
Unstaking Tokens (Withdraw): Withdraw money from DApp. fetch staking balance require amount greter than 0 transfer Mock Dai tokens to this contract for staking reset staking balance update staking status
function unstakeTokens() public { uint balance = stakingBalance[msg.sender]; require(balance > 0, "staking balance cannot be 0"); daiToken.transfer(msg.sender, balance); stakingBalance[msg.sender] = 0; isStaking[msg.sender] = false; } Core Thing: Distribute DApp tokens as interest and also allow the investor to unstake their tokens from the app so give them interest using the app. */
12,661,400
pragma solidity 0.6.12; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IERC20Burnable.sol"; import {YearnVaultAdapterWithIndirection} from "./adapters/YearnVaultAdapterWithIndirection.sol"; import {VaultWithIndirection} from "./libraries/alchemist/VaultWithIndirection.sol"; import {ITransmuter} from "./interfaces/ITransmuter.sol"; // ___ __ __ _ ___ __ _ // / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_) // / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _ // /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_) // // .___________..______ ___ .__ __. _______..___ ___. __ __ .___________. _______ .______ // | || _ \ / \ | \ | | / || \/ | | | | | | || ____|| _ \ // `---| |----`| |_) | / ^ \ | \| | | (----`| \ / | | | | | `---| |----`| |__ | |_) | // | | | / / /_\ \ | . ` | \ \ | |\/| | | | | | | | | __| | / // | | | |\ \----. / _____ \ | |\ | .----) | | | | | | `--' | | | | |____ | |\ \----. // |__| | _| `._____|/__/ \__\ |__| \__| |_______/ |__| |__| \______/ |__| |_______|| _| `._____| /** * @dev Implementation of the {IERC20Burnable} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20Burnable-approve}. */ contract TransmuterB is Context { using SafeMath for uint256; using SafeERC20 for IERC20Burnable; using Address for address; using VaultWithIndirection for VaultWithIndirection.Data; using VaultWithIndirection for VaultWithIndirection.List; address public constant ZERO_ADDRESS = address(0); uint256 public transmutationPeriod; address public alToken; address public token; mapping(address => uint256) public depositedAlTokens; mapping(address => uint256) public tokensInBucket; mapping(address => uint256) public realisedTokens; mapping(address => uint256) public lastDividendPoints; mapping(address => bool) public userIsKnown; mapping(uint256 => address) public userList; uint256 public nextUser; uint256 public totalSupplyAltokens; uint256 public buffer; uint256 public lastDepositBlock; ///@dev values needed to calculate the distribution of base asset in proportion for alTokens staked uint256 public pointMultiplier = 10e18; uint256 public totalDividendPoints; uint256 public unclaimedDividends; /// @dev alchemist addresses whitelisted mapping (address => bool) public whiteList; /// @dev addresses whitelisted to run keepr jobs (harvest) mapping (address => bool) public keepers; /// @dev The threshold above which excess funds will be deployed to yield farming activities uint256 public plantableThreshold = 5000000000000000000000000; // 5mm /// @dev The % margin to trigger planting or recalling of funds uint256 public plantableMargin = 5; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; /// @dev The address of the account which can perform emergency activities address public sentinel; /// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall /// from the active vault. bool public pause; /// @dev The address of the contract which will receive fees. address public rewards; /// @dev A mapping of adapter addresses to keep track of vault adapters that have already been added mapping(YearnVaultAdapterWithIndirection => bool) public adapters; /// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for /// deposits and withdraws. VaultWithIndirections before the last element are considered inactive and are expected to be cleared. VaultWithIndirection.List private _vaults; /// @dev make sure the contract is only initialized once. bool public initialized; /// @dev mapping of user account to the last block they acted mapping(address => uint256) public lastUserAction; /// @dev number of blocks to delay between allowed user actions uint256 public minUserActionDelay; event GovernanceUpdated( address governance ); event PendingGovernanceUpdated( address pendingGovernance ); event SentinelUpdated( address sentinel ); event TransmuterPeriodUpdated( uint256 newTransmutationPeriod ); event TokenClaimed( address claimant, address token, uint256 amountClaimed ); event AlUsdStaked( address staker, uint256 amountStaked ); event AlUsdUnstaked( address staker, uint256 amountUnstaked ); event Transmutation( address transmutedTo, uint256 amountTransmuted ); event ForcedTransmutation( address transmutedBy, address transmutedTo, uint256 amountTransmuted ); event Distribution( address origin, uint256 amount ); event WhitelistSet( address whitelisted, bool state ); event KeepersSet( address[] keepers, bool[] states ); event PlantableThresholdUpdated( uint256 plantableThreshold ); event PlantableMarginUpdated( uint256 plantableMargin ); event MinUserActionDelayUpdated( uint256 minUserActionDelay ); event ActiveVaultUpdated( YearnVaultAdapterWithIndirection indexed adapter ); event PauseUpdated( bool status ); event FundsRecalled( uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue ); event FundsHarvested( uint256 withdrawnAmount, uint256 decreasedValue ); event RewardsUpdated( address treasury ); event MigrationComplete( address migrateTo, uint256 fundsMigrated ); constructor(address _alToken, address _token, address _governance) public { require(_governance != ZERO_ADDRESS, "Transmuter: 0 gov"); governance = _governance; alToken = _alToken; token = _token; transmutationPeriod = 500000; minUserActionDelay = 1; pause = true; } ///@return displays the user's share of the pooled alTokens. function dividendsOwing(address account) public view returns (uint256) { uint256 newDividendPoints = totalDividendPoints.sub(lastDividendPoints[account]); return depositedAlTokens[account].mul(newDividendPoints).div(pointMultiplier); } /// @dev Checks that caller is not a eoa. /// /// This is used to prevent contracts from interacting. modifier noContractAllowed() { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "no contract calls"); _; } ///@dev modifier to fill the bucket and keep bookkeeping correct incase of increase/decrease in shares modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); tokensInBucket[account] = tokensInBucket[account].add(owing); } lastDividendPoints[account] = totalDividendPoints; _; } ///@dev modifier add users to userlist. Users are indexed in order to keep track of when a bond has been filled modifier checkIfNewUser() { if (!userIsKnown[msg.sender]) { userList[nextUser] = msg.sender; userIsKnown[msg.sender] = true; nextUser++; } _; } ///@dev run the phased distribution of the buffered funds modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; // check if there is something in bufffer if (_buffer > 0) { // NOTE: if last deposit was updated in the same block as the current call // then the below logic gates will fail //calculate diffrence in time uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); // distribute all if bigger than timeframe if(deltaTime >= transmutationPeriod) { _toDistribute = _buffer; } else { //needs to be bigger than 0 cuzz solidity no decimals if(_buffer.mul(deltaTime) > transmutationPeriod) { _toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod); } } // factually allocate if any needs distribution if(_toDistribute > 0){ // remove from buffer buffer = _buffer.sub(_toDistribute); // increase the allocation increaseAllocations(_toDistribute); } } // current timeframe is now the last lastDepositBlock = _currentBlock; _; } /// @dev A modifier which checks if whitelisted for minting. modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; } /// @dev A modifier which checks if caller is a keepr. modifier onlyKeeper() { require(keepers[msg.sender], "Transmuter: !keeper"); _; } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; } /// @dev checks that the block delay since a user's last action is longer than the minium delay /// modifier ensureUserActionDelay() { require(block.number.sub(lastUserAction[msg.sender]) >= minUserActionDelay, "action delay not met"); lastUserAction[msg.sender] = block.number; _; } ///@dev set the transmutationPeriod variable /// /// sets the length (in blocks) of one full distribution phase function setTransmutationPeriod(uint256 newTransmutationPeriod) public onlyGov() { transmutationPeriod = newTransmutationPeriod; emit TransmuterPeriodUpdated(transmutationPeriod); } ///@dev claims the base token after it has been transmuted /// ///This function reverts if there is no realisedToken balance function claim() public noContractAllowed() { address sender = msg.sender; require(realisedTokens[sender] > 0); uint256 value = realisedTokens[sender]; realisedTokens[sender] = 0; ensureSufficientFundsExistLocally(value); IERC20Burnable(token).safeTransfer(sender, value); emit TokenClaimed(sender, token, value); } ///@dev Withdraws staked alTokens from the transmuter /// /// This function reverts if you try to draw more tokens than you deposited /// ///@param amount the amount of alTokens to unstake function unstake(uint256 amount) public noContractAllowed() updateAccount(msg.sender) { // by calling this function before transmuting you forfeit your gained allocation address sender = msg.sender; require(depositedAlTokens[sender] >= amount,"Transmuter: unstake amount exceeds deposited amount"); depositedAlTokens[sender] = depositedAlTokens[sender].sub(amount); totalSupplyAltokens = totalSupplyAltokens.sub(amount); IERC20Burnable(alToken).safeTransfer(sender, amount); emit AlUsdUnstaked(sender, amount); } ///@dev Deposits alTokens into the transmuter /// ///@param amount the amount of alTokens to stake function stake(uint256 amount) public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) checkIfNewUser() { require(!pause, "emergency pause enabled"); // requires approval of AlToken first address sender = msg.sender; //require tokens transferred in; IERC20Burnable(alToken).safeTransferFrom(sender, address(this), amount); totalSupplyAltokens = totalSupplyAltokens.add(amount); depositedAlTokens[sender] = depositedAlTokens[sender].add(amount); emit AlUsdStaked(sender, amount); } /// @dev Converts the staked alTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket /// /// once the alToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim() /// /// reverts if there are no pendingdivs or tokensInBucket function transmute() public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) { address sender = msg.sender; uint256 pendingz = tokensInBucket[sender]; uint256 diff; require(pendingz > 0, "need to have pending in bucket"); tokensInBucket[sender] = 0; // check bucket overflow if (pendingz > depositedAlTokens[sender]) { diff = pendingz.sub(depositedAlTokens[sender]); // remove overflow pendingz = depositedAlTokens[sender]; } // decrease altokens depositedAlTokens[sender] = depositedAlTokens[sender].sub(pendingz); // BURN ALTOKENS IERC20Burnable(alToken).burn(pendingz); // adjust total totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); // reallocate overflow increaseAllocations(diff); // add payout realisedTokens[sender] = realisedTokens[sender].add(pendingz); emit Transmutation(sender, pendingz); } /// @dev Executes transmute() on another account that has had more base tokens allocated to it than alTokens staked. /// /// The caller of this function will have the surlus base tokens credited to their tokensInBucket balance, rewarding them for performing this action /// /// This function reverts if the address to transmute is not over-filled. /// /// @param toTransmute address of the account you will force transmute. function forceTransmute(address toTransmute) public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) updateAccount(toTransmute) checkIfNewUser() { //load into memory address sender = msg.sender; uint256 pendingz = tokensInBucket[toTransmute]; // check restrictions require( pendingz > depositedAlTokens[toTransmute], "Transmuter: !overflow" ); // empty bucket tokensInBucket[toTransmute] = 0; // calculaate diffrence uint256 diff = pendingz.sub(depositedAlTokens[toTransmute]); // remove overflow pendingz = depositedAlTokens[toTransmute]; // decrease altokens depositedAlTokens[toTransmute] = 0; // BURN ALTOKENS IERC20Burnable(alToken).burn(pendingz); // adjust total totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); // reallocate overflow tokensInBucket[sender] = tokensInBucket[sender].add(diff); // add payout realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz); uint256 value = realisedTokens[toTransmute]; ensureSufficientFundsExistLocally(value); // force payout of realised tokens of the toTransmute address realisedTokens[toTransmute] = 0; IERC20Burnable(token).safeTransfer(toTransmute, value); emit ForcedTransmutation(sender, toTransmute, value); } /// @dev Transmutes and unstakes all alTokens /// /// This function combines the transmute and unstake functions for ease of use function exit() public noContractAllowed() { transmute(); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } /// @dev Transmutes and claims all converted base tokens. /// /// This function combines the transmute and claim functions while leaving your remaining alTokens staked. function transmuteAndClaim() public noContractAllowed() { transmute(); claim(); } /// @dev Transmutes, claims base tokens, and withdraws alTokens. /// /// This function helps users to exit the transmuter contract completely after converting their alTokens to the base pair. function transmuteClaimAndWithdraw() public noContractAllowed() { transmute(); claim(); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } /// @dev Distributes the base token proportionally to all alToken stakers. /// /// This function is meant to be called by the Alchemist contract for when it is sending yield to the transmuter. /// Anyone can call this and add funds, idk why they would do that though... /// /// @param origin the account that is sending the tokens to be distributed. /// @param amount the amount of base tokens to be distributed to the transmuter. function distribute(address origin, uint256 amount) public onlyWhitelisted() runPhasedDistribution() { require(!pause, "emergency pause enabled"); IERC20Burnable(token).safeTransferFrom(origin, address(this), amount); buffer = buffer.add(amount); _plantOrRecallExcessFunds(); emit Distribution(origin, amount); } /// @dev Allocates the incoming yield proportionally to all alToken stakers. /// /// @param amount the amount of base tokens to be distributed in the transmuter. function increaseAllocations(uint256 amount) internal { if(totalSupplyAltokens > 0 && amount > 0) { totalDividendPoints = totalDividendPoints.add( amount.mul(pointMultiplier).div(totalSupplyAltokens) ); unclaimedDividends = unclaimedDividends.add(amount); } else { buffer = buffer.add(amount); } } /// @dev Gets the status of a user's staking position. /// /// The total amount allocated to a user is the sum of pendingdivs and inbucket. /// /// @param user the address of the user you wish to query. /// /// returns user status function userInfo(address user) public view returns ( uint256 depositedAl, uint256 pendingdivs, uint256 inbucket, uint256 realised ) { uint256 _depositedAl = depositedAlTokens[user]; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } uint256 _pendingdivs = _toDistribute.mul(depositedAlTokens[user]).div(totalSupplyAltokens); uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user)); uint256 _realised = realisedTokens[user]; return (_depositedAl, _pendingdivs, _inbucket, _realised); } /// @dev Gets the status of multiple users in one call /// /// This function is used to query the contract to check for /// accounts that have overfilled positions in order to check /// who can be force transmuted. /// /// @param from the first index of the userList /// @param to the last index of the userList /// /// returns the userList with their staking status in paginated form. function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; address[] memory _theUserList = new address[](delta); //user uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedAlTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedAlTokens[userList[i]]).div(totalSupplyAltokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } /// @dev Gets info on the buffer /// /// This function is used to query the contract to get the /// latest state of the buffer /// /// @return _toDistribute the amount ready to be distributed /// @return _deltaBlocks the amount of time since the last phased distribution /// @return _buffer the amount in the buffer function bufferInfo() public view returns (uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer){ _deltaBlocks = block.number.sub(lastDepositBlock); _buffer = buffer; _toDistribute = _buffer.mul(_deltaBlocks).div(transmutationPeriod); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov() { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance,"!pendingGovernance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } /// @dev Sets the whitelist /// /// This function reverts if the caller is not governance /// /// @param _toWhitelist the address to alter whitelist permissions. /// @param _state the whitelist state. function setWhitelist(address _toWhitelist, bool _state) external onlyGov() { whiteList[_toWhitelist] = _state; emit WhitelistSet(_toWhitelist, _state); } /// @dev Sets the keeper list /// /// This function reverts if the caller is not governance /// /// @param _keepers the accounts to set states for. /// @param _states the accounts states. function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov() { uint256 n = _keepers.length; for(uint256 i = 0; i < n; i++) { keepers[_keepers[i]] = _states[i]; } emit KeepersSet(_keepers, _states); } /// @dev Initializes the contract. /// /// This function checks that the transmuter and rewards have been set and sets up the active vault. /// /// @param _adapter the vault adapter of the active vault. function initialize(YearnVaultAdapterWithIndirection _adapter) external onlyGov { require(!initialized, "Transmuter: already initialized"); require(rewards != ZERO_ADDRESS, "Transmuter: cannot initialize rewards address to 0x0"); _updateActiveVault(_adapter); initialized = true; } function migrate(YearnVaultAdapterWithIndirection _adapter) external onlyGov() { _updateActiveVault(_adapter); } /// @dev Updates the active vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the new active vault. function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal { require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), "Transmuter: active vault address cannot be 0x0."); require(address(_adapter.token()) == token, "Transmuter.vault: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(VaultWithIndirection.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); } /// @dev Gets the number of vaults in the vault list. /// /// @return the vault count. function vaultCount() external view returns (uint256) { return _vaults.length(); } /// @dev Get the adapter of a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the vault adapter. function getVaultAdapter(uint256 _vaultId) external view returns (address) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); return address(_vault.adapter); } /// @dev Get the total amount of the parent asset that has been deposited into a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the total amount of deposited tokens. function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } /// @dev Recalls funds from active vault if less than amt exist locally /// /// @param amt amount of funds that need to exist locally to fulfill pending request function ensureSufficientFundsExistLocally(uint256 amt) internal { uint256 currentBal = IERC20Burnable(token).balanceOf(address(this)); if (currentBal < amt) { uint256 diff = amt - currentBal; // get enough funds from active vault to replenish local holdings & fulfill claim request _recallExcessFundsFromActiveVault(plantableThreshold.add(diff)); } } /// @dev Recalls all planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds function recallAllFundsFromVault(uint256 _vaultId) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallAllFundsFromVault(_vaultId); } /// @dev Recalls all planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds function _recallAllFundsFromVault(uint256 _vaultId) internal { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdrawAll(address(this)); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } /// @dev Recalls planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds /// @param _amount the amount of funds to recall function recallFundsFromVault(uint256 _vaultId, uint256 _amount) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallFundsFromVault(_vaultId, _amount); } /// @dev Recalls planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds /// @param _amount the amount of funds to recall function _recallFundsFromVault(uint256 _vaultId, uint256 _amount) internal { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } /// @dev Recalls planted funds from the active vault /// /// @param _amount the amount of funds to recall function _recallFundsFromActiveVault(uint256 _amount) internal { _recallFundsFromVault(_vaults.lastIndex(), _amount); } /// @dev Plants or recalls funds from the active vault /// /// This function plants excess funds in an external vault, or recalls them from the external vault /// Should only be called as part of distribute() function _plantOrRecallExcessFunds() internal { // check if the transmuter holds more funds than plantableThreshold uint256 bal = IERC20Burnable(token).balanceOf(address(this)); uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100); if (bal > plantableThreshold.add(marginVal)) { uint256 plantAmt = bal - plantableThreshold; // if total funds above threshold, send funds to vault VaultWithIndirection.Data storage _activeVault = _vaults.last(); _activeVault.deposit(plantAmt); } else if (bal < plantableThreshold.sub(marginVal)) { // if total funds below threshold, recall funds from vault // first check that there are enough funds in vault uint256 harvestAmt = plantableThreshold - bal; _recallExcessFundsFromActiveVault(harvestAmt); } } /// @dev Recalls up to the harvestAmt from the active vault /// /// This function will recall less than harvestAmt if only less is available /// /// @param _recallAmt the amount to harvest from the active vault function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal { VaultWithIndirection.Data storage _activeVault = _vaults.last(); uint256 activeVaultVal = _activeVault.totalValue(); if (activeVaultVal < _recallAmt) { _recallAmt = activeVaultVal; } if (_recallAmt > 0) { _recallFundsFromActiveVault(_recallAmt); } } /// @dev Sets the address of the sentinel /// /// @param _sentinel address of the new sentinel function setSentinel(address _sentinel) external onlyGov() { require(_sentinel != ZERO_ADDRESS, "Transmuter: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } /// @dev Sets the threshold of total held funds above which excess funds will be planted in yield farms. /// /// This function reverts if the caller is not the current governance. /// /// @param _plantableThreshold the new plantable threshold. function setPlantableThreshold(uint256 _plantableThreshold) external onlyGov() { plantableThreshold = _plantableThreshold; emit PlantableThresholdUpdated(_plantableThreshold); } /// @dev Sets the plantableThreshold margin for triggering the planting or recalling of funds on harvest /// /// This function reverts if the caller is not the current governance. /// /// @param _plantableMargin the new plantable margin. function setPlantableMargin(uint256 _plantableMargin) external onlyGov() { plantableMargin = _plantableMargin; emit PlantableMarginUpdated(_plantableMargin); } /// @dev Sets the minUserActionDelay /// /// This function reverts if the caller is not the current governance. /// /// @param _minUserActionDelay the new min user action delay. function setMinUserActionDelay(uint256 _minUserActionDelay) external onlyGov() { minUserActionDelay = _minUserActionDelay; emit MinUserActionDelayUpdated(_minUserActionDelay); } /// @dev Sets if the contract should enter emergency exit mode. /// /// There are 2 main reasons to pause: /// 1. Need to shut down deposits in case of an emergency in one of the vaults /// 2. Need to migrate to a new transmuter /// /// While the transmuter is paused, deposit() and distribute() are disabled /// /// @param _pause if the contract should enter emergency exit mode. function setPause(bool _pause) external { require(msg.sender == governance || msg.sender == sentinel, "!(gov || sentinel)"); pause = _pause; emit PauseUpdated(_pause); } /// @dev Harvests yield from a vault. /// /// @param _vaultId the identifier of the vault to harvest from. /// /// @return the amount of funds that were harvested from the vault. function harvest(uint256 _vaultId) external onlyKeeper() returns (uint256, uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(rewards); emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } /// @dev Sets the rewards contract. /// /// This function reverts if the new rewards contract is the zero address or the caller is not the current governance. /// /// @param _rewards the new rewards contract. function setRewards(address _rewards) external onlyGov() { // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_rewards != ZERO_ADDRESS, "Transmuter: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } /// @dev Migrates transmuter funds to a new transmuter /// /// @param migrateTo address of the new transmuter function migrateFunds(address migrateTo) external onlyGov() { require(migrateTo != address(0), "cannot migrate to 0x0"); require(pause, "migrate: set emergency exit first"); // leave enough funds to service any pending transmutations uint256 totalFunds = IERC20Burnable(token).balanceOf(address(this)); uint256 migratableFunds = totalFunds.sub(totalSupplyAltokens, "not enough funds to service stakes"); IERC20Burnable(token).approve(migrateTo, migratableFunds); ITransmuter(migrateTo).distribute(address(this), migratableFunds); emit MigrationComplete(migrateTo, migratableFunds); } }
Harvests yield from a vault. _vaultId the identifier of the vault to harvest from. return the amount of funds that were harvested from the vault.
function harvest(uint256 _vaultId) external onlyKeeper() returns (uint256, uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(rewards); emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); }
2,510,766
./full_match/80001/0xfA648f03E25206F41b6CFAA6fC0F10DB971321c1/sources/contracts/StreamingFeeModule.sol
Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets minted to manager. _setToken SetToken instance _feeQuantity Amount of Sets to be minted as fees return uint256 Amount of Sets accrued to manager as fee return uint256 Amount of Sets accrued to protocol as fee/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity) internal returns (uint256, uint256) { address protocolFeeRecipient = controller.feeRecipient(); uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX); uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee); uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount); _setToken.mint(_feeRecipient(_setToken), managerFeeAmount); if (protocolFeeAmount > 0) { _setToken.mint(protocolFeeRecipient, protocolFeeAmount); } return (managerFeeAmount, protocolFeeAmount); }
840,679
pragma solidity ^0.4.18; // 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/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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&#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, 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; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // 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: zeppelin-solidity/contracts/token/ERC20/PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/WealthE.sol contract WealthE is MintableToken, PausableToken, Claimable { /*----------- ERC20 GLOBALS -----------*/ string public constant name = "Wealth-E"; string public constant symbol = "WRE"; uint8 public constant decimals = 18; /*----------- Ownership Reclaim -----------*/ address public reclaimableOwner; /** * @dev Restricts method call to only the address set as `reclaimableOwner`. */ modifier onlyReclaimableOwner() { require(msg.sender == reclaimableOwner); _; } /** * @dev Sets the reclaim address to current owner. */ function setupReclaim() public onlyOwner { require(reclaimableOwner == address(0)); reclaimableOwner = msg.sender; } /** * @dev Resets the reclaim address to address(0). */ function resetReclaim() public onlyReclaimableOwner { reclaimableOwner = address(0); } /** * @dev Failsafe to reclaim ownership in the event crowdsale is unable to * return ownership. Reclaims ownership regardless of * pending ownership transfer. */ function reclaimOwnership() public onlyReclaimableOwner { // Erase any pending transfer. pendingOwner = address(0); // Transfer ownership. OwnershipTransferred(owner, reclaimableOwner); owner = reclaimableOwner; // Reset reclaimableOwner. reclaimableOwner = address(0); } }
Failsafe to reclaim ownership in the event crowdsale is unable to return ownership. Reclaims ownership regardless of pending ownership transfer./ Erase any pending transfer. Transfer ownership. Reset reclaimableOwner.
function reclaimOwnership() public onlyReclaimableOwner { pendingOwner = address(0); OwnershipTransferred(owner, reclaimableOwner); owner = reclaimableOwner; reclaimableOwner = address(0); }
6,618,887
./full_match/1/0x7C888C0cAC0886a4FF6D1A4d26f93BFD9698d618/sources/contracts/crosschain/circle-cctp/CircleCctpGateway.sol
Sets the address of the processing fee collector _processingFeeCollector The address of the processing fee collector/
function setProcessingFeeCollector(address _processingFeeCollector) external onlyManager { _setProcessingFeeCollector(_processingFeeCollector); }
3,094,860
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "openzeppelin-solidity/contracts/access/Ownable.sol"; import "openzeppelin-solidity/contracts/utils/Context.sol"; import "openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/interfaces/IERC165.sol"; import "openzeppelin-solidity/contracts/interfaces/IERC721.sol"; import "openzeppelin-solidity/contracts/interfaces/IERC721Enumerable.sol"; import "openzeppelin-solidity/contracts/interfaces/IERC721Metadata.sol"; import "openzeppelin-solidity/contracts/interfaces/IERC721Receiver.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "openzeppelin-solidity/contracts/utils/structs/EnumerableMap.sol"; import "openzeppelin-solidity/contracts/utils/Strings.sol"; 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; } } /** * @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; modifier onlyTradableTexugo (address from, uint256 tokenId) { require(tokenId < 20020, "Out of tokenId"); require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); _; } struct Offer { bool isForSale; uint256 texugoIndex; address seller; uint256 minValue; address onlySellTo; } struct Bid { bool hasBid; uint256 texugoIndex; address bidder; uint256 value; } mapping(uint256 => uint256) private assignOrders; mapping (uint256 => Offer) public texugosOfferedForSale; mapping (uint256 => Bid) public texugoBids; mapping (address => uint256) public pendingWithdrawals; // 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_) { _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); } function _approve(address to, uint256 tokenId) private { _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 { } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ /** * @dev Collection of functions related to the address type */ contract ContractBurger is ERC721, Ownable { using SafeMath for uint256; using Strings for uint256; mapping(uint256 => uint256) private assignOrders; uint256 public SALE_START_TIMESTAMP = 1 ; // 1628535570 uint256 public constant MAX_SUPPLY = 20020; uint256 public texugosRemainingToAssign = MAX_SUPPLY; uint256 public constant MAX_RESERVE = 10; uint256 public reserved = 0; uint256 public randIndex = 0; uint256 public texugoIndex =0; // Base URI address private _donationRecipient; address private _addressDraw1; address private _royalRecipient; //uint256[] private drawAmounts = [1 ether, 2 ether, 5 ether]; //Prod represents [2021, 7071, ALL] uint256 public unitprice = 1 ether/10; uint256[] public drawAmounts = [1 ether, 2 ether, 3 ether]; //tests uint public constant drawAfterTotalSupply = 3 ether / 10; // define a reasonable value for open market draw uint256 public dateDraw1; //Better make private after validations uint256 public fundsDon = 0; uint256 public fundsDraw = 0; uint256 public fundsRoyal = 0; uint256 public currentDraw = 0; address constant private nul = 0x0000000000000000000000000000000000000000; string public _dataVault; string public constant imageHash = "notneeded-after-erc721"; function changeDonationRecipient(address donationRecipient) onlyOwner public { _changeDonationRecipient(donationRecipient); } function _changeDonationRecipient(address donationRecipient_) internal virtual { _donationRecipient = donationRecipient_; } function getDonationRecipient() public view virtual returns (address ) { return _donationRecipient; } function withdrawDonation() external { require(msg.sender == _donationRecipient); //uint256 don = address(this).balance / 2 uint256 f = fundsDon; fundsDon = 0; payable(msg.sender).transfer(f); } function changeRoyalRecipient(address royalRecipient) onlyOwner public { _changeRoyalRecipient(royalRecipient); } function _changeRoyalRecipient(address royalRecipient_) internal virtual { _royalRecipient = royalRecipient_; } function getRoyalRecipient() public view virtual returns (address ) { return _royalRecipient; } function withdrawRoyal() external { require(msg.sender == _royalRecipient); //uint256 don = address(this).balance / 2 uint256 f = fundsRoyal; fundsRoyal = 0; payable(msg.sender).transfer(f); } function changeDraw1Recipient(address draw1Recipient) internal { _changeDraw1Recipient(draw1Recipient); } function _changeDraw1Recipient(address draw1Recipient_) internal virtual { _addressDraw1 = draw1Recipient_; } function getDraw1Recipient() public view virtual returns (address ) { return _addressDraw1; } function withdrawFundsDraw() external { require(msg.sender == _addressDraw1,"Address not Eligible"); uint256 prize = (currentDraw < 3) ? drawAmounts[currentDraw] : drawAfterTotalSupply; require(fundsDraw > prize,"Not enough Burgers sold yet"); fundsDraw = fundsDraw - prize; currentDraw +=1; _changeDraw1Recipient(nul); payable(msg.sender).transfer(prize); } function doDraw() internal { changeDraw1Recipient(ownerOf(tokenByIndex(_random(totalSupply()) % totalSupply()))); /* uint256 winnerTokenId = _random(totalSupply) % totalSupply; uint256 winnerToken = tokenByIndex(winnerTokenId); address winnerAddr = ownerOf(winnerToken); */ } function dataVaultOnChain(string memory dataVault) public { _dataVaultOnChain(dataVault); } function _dataVaultOnChain(string memory dataVault_) internal virtual { _dataVault = dataVault_; } constructor(string memory name, string memory symbol, string memory baseURI) ERC721(name, symbol) { _setBaseURI(baseURI); } /* function reserveNFTs(uint256 amount) onlyOwner public { require(SafeMath.add(totalSupply(), amount) <= MAX_SUPPLY, "Exceeds maximum supply. Please try to mint less Nfts."); require(reserved.add(amount) <= MAX_RESERVE, "Exceeds maximum reserve. Please try to mint less Nfts."); for (uint i = 0; i < amount; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } reserved += amount; }*/ function setSaleTimestamp(uint256 new_SALE_START_TIMESTAMP) onlyOwner public { SALE_START_TIMESTAMP = new_SALE_START_TIMESTAMP; } function getNFTPrice(uint256 amount) public view returns (uint256) { require(totalSupply() < MAX_SUPPLY, "Sale has already ended."); return amount.mul(unitprice); } function _random(uint256 capme) internal view returns(uint256) { return uint256( keccak256( abi.encodePacked(block.timestamp + block.difficulty + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / block.timestamp) + block.gaslimit + ((uint256(keccak256(abi.encodePacked(_msgSender())))) / block.timestamp) + block.number) ) ) / capme; } function _fillAssignOrder(uint256 orderA, uint256 orderB) internal returns(uint256) { uint256 temp = orderA; if (assignOrders[orderA] > 0) temp = assignOrders[orderA]; assignOrders[orderA] = orderB; if (assignOrders[orderB] > 0) assignOrders[orderA] = assignOrders[orderB]; assignOrders[orderB] = temp; return assignOrders[orderA]; } function mintBurger(uint256 amount) public payable { // require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started yet."); require(totalSupply() < MAX_SUPPLY, "Sale has already ended."); require(amount > 0, "You cannot mint 0 Nfts."); require(amount <= 20, "You cannot mint more than 20 Nfts per once"); require(SafeMath.add(totalSupply(), amount) <= MAX_SUPPLY, "Exceeds maximum supply. Please try to mint less Nfts."); require(getNFTPrice(amount) == msg.value, "Amount of Ether sent is not correct."); fundsDraw += (msg.value * 5 /100); fundsDon += (msg.value * 5 /100); fundsRoyal += (msg.value * 45 /100); (bool success,) = owner().call{value: (msg.value * 45 ) /100}(""); require(success); for (uint i = 0; i < amount; i++) { randIndex = _random(texugosRemainingToAssign) % texugosRemainingToAssign; texugoIndex = _fillAssignOrder(--texugosRemainingToAssign, randIndex); _safeMint(msg.sender, texugoIndex); } if (fundsDraw > drawAmounts[currentDraw]){ doDraw(); } } unction buyTexugo(uint256 tokenId) payable public { Offer memory offer = texugosOfferedForSale[tokenId]; require(tokenId < MAX_SUPPLY, "Out of tokenId"); require(offer.isForSale, "No Sale"); require(offer.onlySellTo == address(0) || offer.onlySellTo == _msgSender(), "Unable to sell"); require(msg.value >= offer.minValue, "Insufficient amount"); require(ownerOf(tokenId) == offer.seller, "Not seller"); address seller = offer.seller; // Transfer the NFT _safeTransfer(seller, _msgSender(), tokenId, ""); pendingWithdrawals[seller] += msg.value * 95 / 100; // handle (bool success,) = owner().call{value: msg.value * 25 / 1000}(""); fundsDon += msg.value * 13 / 1000; fundsDraw += msg.value * 12 / 1000; if (fundsDraw > drawAmounts[currentDraw]){ doDraw(); } require(success); // handle // emit TexugoBought(tokenId, msg.value, seller, _msgSender()); } function texugoNoLongerForSale(uint256 tokenId) public { _texugoNoLongerForSale(_msgSender(), tokenId); } function _texugoNoLongerForSale(address from, uint256 tokenId) internal onlyTradableTexugo(from, tokenId) { texugosOfferedForSale[tokenId] = Offer(false, tokenId, from, 0, address(0)); // emit TexugoNoLongerForSale(tokenId); } function offerTexugoForSale(uint256 tokenId, uint256 minSalePriceInWei) public onlyTradableTexugo(_msgSender(), tokenId) { texugosOfferedForSale[tokenId] = Offer(true, tokenId, _msgSender(), minSalePriceInWei, address(0)); // emit TexugoOffered(tokenId, minSalePriceInWei, address(0)); } function enterBidForTexugo(uint256 tokenId) public payable { require(tokenId < MAX_SUPPLY, "Out"); require(ownerOf(tokenId) != _msgSender(), "Invalid"); require(msg.value > texugoBids[tokenId].value, "Invalid"); Bid memory existing = texugoBids[tokenId]; if (existing.value > 0) { // Refund the failing bid pendingWithdrawals[existing.bidder] += existing.value; } texugoBids[tokenId] = Bid(true, tokenId, _msgSender(), msg.value); // emit TexugoBidEntered(tokenId, msg.value, _msgSender()); } function acceptBidForTexugo(uint256 tokenId, uint256 minPrice) public onlyTradableTexugo(_msgSender(), tokenId) { require(texugoBids[tokenId].value >= minPrice, "Invalid"); Bid memory bid = texugoBids[tokenId]; texugoBids[tokenId] = Bid(false, tokenId, address(0), 0); _safeTransfer(_msgSender(), bid.bidder, tokenId, ""); pendingWithdrawals[_msgSender()] += bid.value * 95 / 100; (bool success,) = owner().call{value: bid.value * 5 / 100}(""); require(success); // emit TexugoBought(tokenId, bid.value, _msgSender(), bid.bidder); } function withdrawBidForTexugo(uint256 tokenId) public { require(tokenId < MAX_SUPPLY, "Out"); require(ownerOf(tokenId) != _msgSender(), "Invalid"); require(texugoBids[tokenId].bidder == _msgSender(), "Invalid"); texugoBids[tokenId] = Bid(false, tokenId, address(0), 0); // Refund the bid money (bool success,) = _msgSender().call{value: texugoBids[tokenId].value}(""); require(success); // emit TexugoBidWithdrawn(tokenId, texugoBids[tokenId].value, _msgSender()); } function transferEther(address payable recipient, uint256 amount) onlyOwner public payable { recipient.transfer(amount); } function withdraw() public { uint256 amount = pendingWithdrawals[_msgSender()]; pendingWithdrawals[_msgSender()] = 0; (bool success,) = _msgSender().call{value: amount}(""); require(success); } function withdraw(uint256 amount) onlyOwner public { payable(msg.sender).transfer(amount); } function changeBaseURI(string memory baseURI) onlyOwner public { _setBaseURI(baseURI); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI(), tokenId.toString())); } }
uint256 don = address(this).balance / 2
function withdrawDonation() external { require(msg.sender == _donationRecipient); uint256 f = fundsDon; fundsDon = 0; payable(msg.sender).transfer(f); }
12,551,165
pragma solidity ^0.4.24; contract FoMoInsurance { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; //********* // STRUCTS //********* struct Player { uint256 id; // player id bytes32 name; // player name uint256 gen; // general vault uint256 aff; // affiliate vault bool isAgent; // referral activated uint256 eth; // eth player has added to round uint256 keys; // keys uint256 units; // uints of insurance uint256 plyrLastSeen; // last day player played uint256 mask; // player mask uint256 level; uint256 accumulatedAff; } //*************** // EXTERNAL DATA //*************** FoMo3Dlong constant private FoMoLong = FoMo3Dlong(0xA62142888ABa8370742bE823c1782D17A0389Da1); DiviesInterface constant private Divies = DiviesInterface(0x93B2dbDd3F242EED7D7c7180c5A4Eddc4BaAE3E7); address constant private community = address(0xe853A139b87dD816f052A60Ef646Fd89f7964545); uint256 public end; bool public ended; //****************** // GLOBAL VARIABLES //****************** mapping(address => mapping(uint256 => uint256)) public unitToExpirePlayer; mapping(uint256 => uint256) public unitToExpire; // unit of insurance due at day x uint256 public issuedInsurance; // all issued insurance uint256 public ethOfKey; // virtual eth of bought keys uint256 public keys; // totalSupply of key uint256 public pot; // eth gonna pay to beneficiary uint256 public today; // today's date uint256 public _now; // current time uint256 public mask; // global mask uint256 public agents; // number of agent // player data mapping(address => Player) public player; // player data mapping(uint256 => address) public agentxID_; // return agent address by id mapping(bytes32 => address) public agentxName_; // return agent address by name // constant parameters uint256 constant maxInsurePeriod = 100; uint256 constant thisRoundIndex = 2; uint256 constant maxLevel = 10; // rate of buying x day insurance uint256[101] public rate = [0, 1000000000000000000, 1990000000000000000, 2970100000000000000, 3940399000000000000, 4900995010000000000, 5851985059900000000, 6793465209301000000, 7725530557207990000, 8648275251635910100, 9561792499119550999, 10466174574128355489, 11361512828387071934, 12247897700103201215, 13125418723102169203, 13994164535871147511, 14854222890512436036, 15705680661607311676, 16548623854991238559, 17383137616441326173, 18209306240276912911, 19027213177874143782, 19836941046095402344, 20638571635634448321, 21432185919278103838, 22217864060085322800, 22995685419484469572, 23765728565289624876, 24528071279636728627, 25282790566840361341, 26029962661171957728, 26769663034560238151, 27501966404214635769, 28226946740172489411, 28944677272770764517, 29655230500043056872, 30358678195042626303, 31055091413092200040, 31744540498961278040, 32427095093971665260, 33102824143031948607, 33771795901601629121, 34434077942585612830, 35089737163159756702, 35738839791528159135, 36381451393612877544, 37017636879676748769, 37647460510879981281, 38270985905771181468, 38888276046713469653, 39499393286246334956, 40104399353383871606, 40703355359850032890, 41296321806251532561, 41883358588189017235, 42464525002307127063, 43039879752284055792, 43609480954761215234, 44173386145213603082, 44731652283761467051, 45284335760923852380, 45831492403314613856, 46373177479281467717, 46909445704488653040, 47440351247443766510, 47965947734969328845, 48486288257619635557, 49001425375043439201, 49511411121293004809, 50016297010080074761, 50516134039979274013, 51010972699579481273, 51500862972583686460, 51985854342857849595, 52465995799429271099, 52941335841434978388, 53411922483020628604, 53877803258190422318, 54339025225608518095, 54795634973352432914, 55247678623618908585, 55695201837382719499, 56138249819008892304, 56576867320818803381, 57011098647610615347, 57440987661134509194, 57866577784523164102, 58287912006677932461, 58705032886611153136, 59117982557745041605, 59526802732167591189, 59931534704845915277, 60332219357797456124, 60728897164219481563, 61121608192577286747, 61510392110651513880, 61895288189544998741, 62276335307649548754, 62653571954573053266, 63027036235027322733, 63396765872677049506]; // threshold of agent upgrade uint256[10] public requirement = [0, 73890560989306501, 200855369231876674, 545981500331442382, 1484131591025766010, 4034287934927351160, 10966331584284585813, 29809579870417282259, 81030839275753838749, 220264657948067161559]; //****************** // EVENT //****************** event UPGRADE (address indexed agent, uint256 level); event BUYINSURANCE(address indexed buyer, uint256 indexed start, uint256 unit, uint256 date); //****************** // MODIFIER //****************** modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev Constructor * @notice Initialize the time */ constructor() public { _now = now; today = _now / 1 days; } /** * @dev Ticker * @notice It is called everytime when a player interacts with this contract * @return true is Fomo3D is ended, false otherwise */ function tick() internal returns(bool) { if (_now != now) { _now = now; uint256 _today; // the current day as soon as ticker is called //check if fomo3D ends (,,end, ended,,,,,,,,) = FoMoLong.round_(thisRoundIndex); if (!ended) { _today = _now / 1 days; } else { _today = end / 1 days; } // calculate the outdated issuedInsurance while (today < _today) { issuedInsurance = issuedInsurance.sub(unitToExpire[today]); today += 1; } } return ended; } /** * @dev Register * @notice Register a name by a human player */ function register(string _nameString) external payable isHuman() { bytes32 _name = _nameString.nameFilter(); address _agent = msg.sender; require(msg.value >= 10000000000000000); require(agentxName_[_name] == address(0)); if(!player[_agent].isAgent){ agents += 1; player[_agent].isAgent = true; player[_agent].id = agents; player[_agent].level = 1; agentxID_[agents] = _agent; } // set name active for the player player[_agent].name = _name; agentxName_[_name] = _agent; if(!community.send(msg.value)){ pot = pot.add(msg.value); } } /** * @dev Upgrade * @notice Upgrade when a player's affiliate bonus meet the promotion */ function upgrade() external isHuman(){ address _agent = msg.sender; require(player[_agent].isAgent); require(player[_agent].level < maxLevel); if(player[_agent].accumulatedAff >= requirement[player[_agent].level]){ player[_agent].level = (1).add(player[_agent].level); emit UPGRADE(_agent,player[_agent].level); } } /** * @dev Buy, using address for referral */ function buyXaddr(address _agent, uint256 _date) isHuman() public payable { // ticker if(tick()){ msg.sender.transfer(msg.value); return; } // validate agent if(!player[_agent].isAgent){ _agent = address(0); } buyCore(msg.sender, msg.value, _date, _agent); } function buyXid(uint256 _agentId, uint256 _date) isHuman() public payable { // ticker if(tick()){ msg.sender.transfer(msg.value); return; } address _agent = agentxID_[_agentId]; // validate agent if(!player[_agent].isAgent){ _agent = address(0); } buyCore(msg.sender, msg.value, _date, _agent); } function buyXname(bytes32 _agentName, uint256 _date) isHuman() public payable { // ticker if(tick()){ msg.sender.transfer(msg.value); return; } address _agent = agentxName_[_agentName]; // validate agent if(!player[_agent].isAgent){ _agent = address(0); } buyCore(msg.sender, msg.value, _date, _agent); } /** * @dev Core part of buying */ function buyCore(address _buyer, uint256 _eth, uint256 _date, address _agent) internal { updatePlayerUnit(_buyer); require(_eth >= 1000000000, "pocket lint: not a valid currency"); if(_date > maxInsurePeriod){ _date = maxInsurePeriod; } uint256 _rate = rate[_date] + 1000000000000000000; uint256 ethToBuyKey = _eth.mul(1000000000000000000) / _rate; //-- ethToBuyKey is a virtual amount used to represent the eth player paid for buying keys, which is usually different from _eth // get value of keys and insurances can be bought uint256 _key = ethOfKey.keysRec(ethToBuyKey); uint256 _unit = (_date == 0)? 0: _key; uint256 newDate = today + _date - 1; // update global data ethOfKey = ethOfKey.add(ethToBuyKey); keys = keys.add(_key); unitToExpire[newDate] = unitToExpire[newDate].add(_unit); issuedInsurance = issuedInsurance.add(_unit); // update player data player[_buyer].eth = player[_buyer].eth.add(_eth); player[_buyer].keys = player[_buyer].keys.add(_key); player[_buyer].units = player[_buyer].units.add(_unit); unitToExpirePlayer[_buyer][newDate] = unitToExpirePlayer[_buyer][newDate].add(_unit); distributeEx(_eth, _agent); distributeIn(_buyer, _eth, _key); emit BUYINSURANCE(_buyer, today, _unit, _date); } /** * @dev Update player's units of insurance */ function updatePlayerUnit(address _player) internal { uint256 _today = player[_player].plyrLastSeen; uint256 expiredUnit = 0; if(_today != 0){ while(_today < today){ expiredUnit = expiredUnit.add(unitToExpirePlayer[_player][_today]); _today += 1; } player[_player].units = player[_player].units.sub(expiredUnit); } player[_player].plyrLastSeen = today; } /** * @dev Distribute to the external */ function distributeEx(uint256 _eth, address _agent) internal { uint256 ex = _eth / 4 ; uint256 affRate; if(player[_agent].isAgent){ affRate = player[_agent].level.add(6); } uint256 _aff = _eth.mul(affRate) / 100; if (_aff > 0) { player[_agent].aff = player[_agent].aff.add(_aff); player[_agent].accumulatedAff = player[_agent].accumulatedAff.add(_aff); } ex = ex.sub(_aff); uint256 _com = ex / 3; uint256 _p3d = ex.sub(_com); if(!community.send(_com)){ pot = pot.add(_com); } Divies.deposit.value(_p3d)(); } /** * @dev Distribute to the internal */ function distributeIn(address _buyer, uint256 _eth, uint256 _keys) internal { uint256 _gen = _eth.mul(3) / 20; // update eth balance (eth = eth - (com share + aff share + p3d share)) _eth = _eth.sub(_eth / 4); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (that's what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_buyer, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot pot = pot.add(_dust).add(_pot); } function updateMasks(address _player, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here is we're going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the global mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calculate profit per key & global mask based on this buy: (dust goes to pot) uint256 _ppt = _gen.mul(1000000000000000000) / keys; mask = mask.add(_ppt); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / 1000000000000000000; player[_player].mask = (((mask.mul(_keys)) / 1000000000000000000).sub(_pearn)).add(player[_player].mask); // calculate & return dust return(_gen.sub( _ppt.mul(keys) / 1000000000000000000)); } /** * @dev Submit a claim from the beneficiary */ function claim() isHuman() public { require(tick()); address beneficiary = msg.sender; updatePlayerUnit(beneficiary); uint256 amount = pot.mul(player[beneficiary].units) / issuedInsurance; player[beneficiary].units = 0; beneficiary.transfer(amount); } /** * @dev Withdraw dividends and aff */ function withdraw() isHuman() public { // setup temp var for player eth uint256 _eth; // get their earnings _eth = withdrawEarnings(msg.sender); // gib moni if (_eth > 0) msg.sender.transfer(_eth); } function withdrawEarnings(address _player) private returns(uint256) { // update gen vault updateGenVault(_player); // from vaults uint256 _earnings = player[_player].gen.add(player[_player].aff); if (_earnings > 0) { player[_player].gen = 0; player[_player].aff = 0; } return(_earnings); } function updateGenVault(address _player) private { uint256 _earnings = calcUnMaskedEarnings(_player); if (_earnings > 0) { // put in gen vault player[_player].gen = _earnings.add(player[_player].gen); // zero out their earnings by updating mask player[_player].mask = _earnings.add(player[_player].mask); } } function calcUnMaskedEarnings(address _player) private view returns(uint256) { return( (mask.mul(player[_player].keys) / 1000000000000000000).sub(player[_player].mask) ); } /** * @dev Return the price buyer will pay for next 1 individual key. * @return Price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { return(keys.add(1000000000000000000).ethRec(1000000000000000000)); } /** * @dev Get the units of insurance of player * @return Amount of existing units of insurance */ function getCurrentUnit(address _player) public view returns(uint256) { uint256 _unit = player[_player].units; uint256 _today = player[_player].plyrLastSeen; uint256 expiredUnit = 0; if(_today != 0){ while(_today < today){ expiredUnit = expiredUnit.add(unitToExpirePlayer[_player][_today]); _today += 1; } } return( _unit == 0 ? 0 : _unit.sub(expiredUnit)); } /** * @dev Get the list of units of insurace going to expire of a player * @return List of units of insurance going to expire from a player */ function getExpiringUnitListPlayer(address _player) public view returns(uint256[maxInsurePeriod] expiringUnitList) { for(uint256 i=0; i<maxInsurePeriod; i++) { expiringUnitList[i] = unitToExpirePlayer[_player][today+i]; } return(expiringUnitList); } /** * @dev Get the list of units of insurace going to expire * @return List of units of insurance going to expire */ function getExpiringUnitList() public view returns(uint256[maxInsurePeriod] expiringUnitList) { for(uint256 i=0; i<maxInsurePeriod; i++){ expiringUnitList[i] = unitToExpire[today+i]; } return(expiringUnitList); } } contract FoMo3Dlong { //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public rID_; // round id number / total rounds that have happened //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; } interface DiviesInterface { function deposit() external payable; } library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } library F3Ddatasets { struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
Withdraw dividends and aff/ setup temp var for player eth get their earnings gib moni
function withdraw() isHuman() public { uint256 _eth; _eth = withdrawEarnings(msg.sender); if (_eth > 0) msg.sender.transfer(_eth); }
2,506,442
pragma solidity 0.4.19; import "../dependencies/aragon-core/contracts/common/DelegateProxy.sol"; import "./STRTokenProxyStorage.sol"; import "./STRToken.sol"; /** * @title Stream Token Proxy * * @dev This contract is a proxy used in front of the Stream Token to make it * upgradable */ contract STRTokenProxy is STRTokenProxyStorage, DelegateProxy { event ImplementationChanged(address previous, address current); event AdminChanged(address previous, address current); /** * @param _admin The address of the admin who can upgrade the token * @param _implementation The address of the current implementation of the * token. It must be a contract */ function STRTokenProxy(address _admin, address _implementation) public { require(_admin != address(0)); proxyAdmin = _admin; setImplementationAndInitializeStorage(_implementation, 0x00); } /** * @dev Forwards everything to the implementation token using a DELEGATECALL */ function () payable public { delegatedFwd(currentImplementation, msg.data); } /** * @dev Changes the token implementation. Only callable by the admin * @param newImplementation It must be a contract * @param data Any data needed by the #migrateStorage(bytes) of the new * implementation. */ function changeTokenImplementation(address newImplementation, bytes32 data) public { require(msg.sender == proxyAdmin); ImplementationChanged(currentImplementation, newImplementation); setImplementationAndInitializeStorage(newImplementation, data); } /** * @dev Changes the admin. Only callable by the current admin */ function changeAdmin(address newAdmin) public { require(msg.sender == proxyAdmin); require(newAdmin != address(0)); AdminChanged(proxyAdmin, newAdmin); proxyAdmin = newAdmin; } /** * @notice We don't declare the state variable as public because that would * pollute the implementation's interface. */ function admin() public constant returns (address) { return proxyAdmin; } /** * @notice We don't declare the state variable as public because that would * pollute the implementation's interface. */ function implementation() public constant returns (address) { return currentImplementation; } function setImplementationAndInitializeStorage( address _implementation, bytes32 data ) internal { require(isContract(_implementation)); currentImplementation = _implementation; assert(currentImplementation.delegatecall( STRToken(_implementation).migrateStorage.selector, data )); } }
_admin The address of the admin who can upgrade the token _implementation The address of the current implementation of the token. It must be a contract/
function STRTokenProxy(address _admin, address _implementation) public { require(_admin != address(0)); proxyAdmin = _admin; setImplementationAndInitializeStorage(_implementation, 0x00); }
7,291,226
./full_match/1/0xd018d5ecCe2Cd1c230F1719367C22DfE92c696ac/sources/contracts/v2/TempleDebtToken.sol
Update the continuously compounding (base) interest rate of all debtors, from this block onwards./ First checkpoint the base interest
function setBaseInterestRate(uint96 _rate) external override onlyElevatedAccess { _getBaseCache(); baseRate = _rate; emit BaseInterestRateSet(_rate); }
8,361,602
// File: contracts/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/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: contracts/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: contracts/ITraits.sol pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/IArena.sol pragma solidity ^0.8.0; interface IArena { function addManyToArenaAndPack(address account, uint16[] calldata tokenIds) external; function randomGuardOwner(uint256 seed) external view returns (address); } // File: contracts/ISquuid.sol pragma solidity ^0.8.0; interface ISquuid { // struct to store each token's traits struct PlayerGuard { bool isPlayer; uint8 colors; uint8 head; uint8 numbers; uint8 shapes; uint8 nose; uint8 accessories; uint8 guns; uint8 feet; uint8 alphaIndex; } function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (PlayerGuard memory); } // File: contracts/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: contracts/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/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: contracts/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/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: contracts/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: contracts/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: contracts/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/ERC20.sol pragma solidity ^0.8.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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/SQUID.sol pragma solidity ^0.8.0; contract SQUID is ERC20, Ownable { // a mapping from an address to whether or not it can mint / burn mapping(address => bool) controllers; constructor() ERC20("SQUID", "SQUID") { } /** * mints $SQUID to a recipient * @param to the recipient of the $SQUID * @param amount the amount of $SQUID to mint */ function mint(address to, uint256 amount) external { require(controllers[msg.sender], "Only controllers can mint"); _mint(to, amount); } /** * burns $SQUID from a holder * @param from the holder of the $SQUID * @param amount the amount of $SQUID to burn */ function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); } /** * enables an address to mint / burn * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } } // File: contracts/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/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: contracts/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/Squuid.sol pragma solidity ^0.8.0; contract Squuid is ISquuid, ERC721Enumerable, Ownable, Pausable { // mint price uint256 public constant WL_MINT_PRICE = .0456 ether; uint256 public constant MINT_PRICE = .06942 ether; // max number of tokens that can be minted - 50000 in production uint256 public immutable MAX_TOKENS; // number of tokens that can be claimed for free - 20% of MAX_TOKENS uint256 public PAID_TOKENS; // number of tokens have been minted so far uint16 public minted; //For Whitelist mapping(address => uint256) public whiteList; //Keep track of data mapping(uint256 => PlayerGuard) public _idData; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => PlayerGuard) public tokenTraits; // mapping from hashed(tokenTrait) to the tokenId it's associated with // used to ensure there are no duplicates mapping(uint256 => uint256) public existingCombinations; // list of probabilities for each trait type // 0 - 9 are associated with Player, 10 - 18 are associated with Wolves uint8[][18] public rarities; // list of aliases for Walker's Alias algorithm // 0 - 9 are associated with Player, 10 - 18 are associated with Wolves uint8[][18] public aliases; // reference to the Arena for choosing random Guard thieves IArena public arena; // reference to $SQUID for burning on mint SQUID public squid; // reference to Traits ITraits public traits; /** * instantiates contract and rarity tables */ constructor(address _squid, address _traits, uint256 _maxTokens) ERC721("Squid Game", 'SGAME') { squid = SQUID(_squid); traits = ITraits(_traits); MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; // I know this looks weird but it saves users gas by making lookup O(1) // A.J. Walker's Alias Algorithm // player // colors rarities[0] = [15, 50, 200, 250, 255]; aliases[0] = [4, 4, 4, 4, 4]; // head rarities[1] = [190, 215, 240, 100, 110, 135, 160, 185, 80, 210, 235, 240, 80, 80, 100, 100, 100, 245, 250, 255]; aliases[1] = [1, 2, 4, 0, 5, 6, 7, 9, 0, 10, 11, 17, 0, 0, 0, 0, 4, 18, 19, 19]; // numbers rarities[2] = [255, 30, 60, 60, 150, 156]; aliases[2] = [0, 0, 0, 0, 0, 0]; // shapes rarities[3] = [221, 100, 181, 140, 224, 147, 84, 228, 140, 224, 250, 160, 241, 207, 173, 84, 254, 220, 196, 140, 168, 252, 140, 183, 236, 252, 224, 255]; aliases[3] = [1, 2, 5, 0, 1, 7, 1, 10, 5, 10, 11, 12, 13, 14, 16, 11, 17, 23, 13, 14, 17, 23, 23, 24, 27, 27, 27, 27]; // nose rarities[4] = [175, 100, 40, 250, 115, 100, 185, 175, 180, 255]; aliases[4] = [3, 0, 4, 6, 6, 7, 8, 8, 9, 9]; // accessories rarities[5] = [80, 225, 227, 228, 112, 240, 64, 160, 167, 217, 171, 64, 240, 126, 80, 255]; aliases[5] = [1, 2, 3, 8, 2, 8, 8, 9, 9, 10, 13, 10, 13, 15, 13, 15]; // guns rarities[6] = [255]; aliases[6] = [0]; // feet rarities[7] = [243, 189, 133, 133, 57, 95, 152, 135, 133, 57, 222, 168, 57, 57, 38, 114, 114, 114, 255]; aliases[7] = [1, 7, 0, 0, 0, 0, 0, 10, 0, 0, 11, 18, 0, 0, 0, 1, 7, 11, 18]; // alphaIndex rarities[8] = [255]; aliases[8] = [0]; // wolves // colors rarities[9] = [210, 90, 9, 9, 9, 150, 9, 255, 9]; aliases[9] = [5, 0, 0, 5, 5, 7, 5, 7, 5]; // head rarities[10] = [255]; aliases[10] = [0]; // numbers rarities[11] = [255]; aliases[11] = [0]; // shapes rarities[12] = [135, 177, 219, 141, 183, 225, 147, 189, 231, 135, 135, 135, 135, 246, 150, 150, 156, 165, 171, 180, 186, 195, 201, 210, 243, 252, 255]; aliases[12] = [1, 2, 3, 4, 5, 6, 7, 8, 13, 3, 6, 14, 15, 16, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 26, 26]; // nose rarities[13] = [255]; aliases[13] = [0]; // accessories rarities[14] = [239, 244, 249, 234, 234, 234, 234, 234, 234, 234, 130, 255, 247]; aliases[14] = [1, 2, 11, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11]; // guns rarities[15] = [75, 180, 165, 120, 60, 150, 105, 195, 45, 225, 75, 45, 195, 120, 255]; aliases[15] = [1, 9, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 14, 12, 14]; // feet rarities[16] = [255]; aliases[16] = [0]; // alphaIndex rarities[17] = [8, 160, 73, 255]; aliases[17] = [2, 3, 3, 3]; } /** EXTERNAL */ /** * mint a token - 90% Player, 10% Wolves * The first 20% are free to claim, the remaining cost $SQUID */ function mint(uint256 amount, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); } else { require(msg.value == 0); } uint256 totalSquidCost = 0; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); generate(minted, seed); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); } else { _safeMint(address(arena), minted); tokenIds[i] = minted; } totalSquidCost += mintCost(minted); } if (totalSquidCost > 0) squid.burn(_msgSender(), totalSquidCost); if (stake) arena.addManyToArenaAndPack(_msgSender(), tokenIds); } function mintWhitelist(uint256 amount, address _wallet, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 5, "Invalid mint amount"); require(whiteList[_msgSender()] >= amount, "Invalid Whitelist Amount"); require(amount * WL_MINT_PRICE == msg.value, "Invalid payment amount"); whiteList[_msgSender()] = whiteList[_msgSender()] - amount; uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); _idData[minted] = generate(minted, seed); if (!stake) { _mint(_wallet, minted); } else { _mint(address(arena), minted); tokenIds[i] = minted; } } if (stake) arena.addManyToArenaAndPack(_msgSender(), tokenIds); } /** * the first 20% are paid in ETH * the next 20% are 20000 $SQUID * the next 40% are 40000 $SQUID * the final 20% are 80000 $SQUID * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function mintCost(uint256 tokenId) public view returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; if (tokenId <= MAX_TOKENS * 2 / 5) return 25000 ether; // XXX if (tokenId <= MAX_TOKENS * 3 / 5) return 75000 ether; // XXX if (tokenId <= MAX_TOKENS * 4 / 5) return 125000 ether; // XXX if (tokenId <= MAX_TOKENS * 9 / 10) return 250000 ether; // XXX return 500000 ether; // XXX } function totalMint() public view returns (uint16) { return minted; } // XXX function transferFrom( address from, address to, uint256 tokenId ) public virtual override { // Hardcode the Arena's approval so that users don't have to waste gas approving if (_msgSender() != address(arena)) require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** INTERNAL */ /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed) internal returns (PlayerGuard memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; return t; } return generate(tokenId, random(seed)); } /** * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup * ensuring O(1) instead of O(n) reduces mint cost by more than 50% * probability & alias tables are generated off-chain beforehand * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[traitType].length); if (seed >> 8 < rarities[traitType][trait]) return trait; return aliases[traitType][trait]; } /** * the first 20% (ETH purchases) go to the minter * the remaining 80% have a 10% chance to be given to a random staked guard * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Guard thief's owner) */ function selectRecipient(uint256 seed) internal view returns (address) { if (minted <= PAID_TOKENS || ((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used address thief = arena.randomGuardOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); return thief; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of randomly selected traits */ function selectTraits(uint256 seed) internal view returns (PlayerGuard memory t) { t.isPlayer = (seed & 0xFFFF) % 10 != 0; uint8 shift = t.isPlayer ? 0 : 9; seed >>= 16; t.colors = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.head = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; t.numbers = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; t.shapes = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; t.nose = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; t.accessories = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; t.guns = selectTrait(uint16(seed & 0xFFFF), 6 + shift); seed >>= 16; t.feet = selectTrait(uint16(seed & 0xFFFF), 7 + shift); seed >>= 16; t.alphaIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift); } /** * converts a struct to a 256 bit hash to check for uniqueness * @param s the struct to pack into a hash * @return the 256 bit hash of the struct */ function structToHash(PlayerGuard memory s) internal pure returns (uint256) { return uint256(bytes32( abi.encodePacked( s.isPlayer, s.colors, s.head, s.shapes, s.accessories, s.guns, s.numbers, s.feet, s.alphaIndex ) )); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } /** READ */ function getTokenTraits(uint256 tokenId) external view override returns (PlayerGuard memory) { return tokenTraits[tokenId]; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } /** ADMIN */ function addToWhitelist(address[] memory toWhitelist) external onlyOwner { for(uint256 i = 0; i < toWhitelist.length; i++){ address idToWhitelist = toWhitelist[i]; whiteList[idToWhitelist] = 3; } } /** * called after deployment so that the contract can get random guard thieves * @param _arena the address of the Arena */ function setArena(address _arena) external onlyOwner { arena = IArena(_arena); } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * updates the number of tokens for sale */ function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } /** RENDER */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return traits.tokenURI(tokenId); } } // File: contracts/Arena.sol pragma solidity ^0.8.0; contract Arena is Ownable, IERC721Receiver, Pausable { // maximum alpha score for a Guard uint8 public constant MAX_ALPHA = 8; // struct to store a stake's token, owner, and earning values struct Stake { uint16 tokenId; uint80 value; address owner; } event TokenStaked(address owner, uint256 tokenId, uint256 value); event PlayerClaimed(uint256 tokenId, uint256 earned, bool unstaked); event GuardClaimed(uint256 tokenId, uint256 earned, bool unstaked); // reference to the Squuid NFT contract Squuid squuid; // reference to the $SQUID contract for minting $SQUID earnings SQUID squid; // maps tokenId to stake mapping(uint256 => Stake) public arena; // maps alpha to all Guard stakes with that alpha mapping(uint256 => Stake[]) public pack; // tracks location of each Guard in Pack mapping(uint256 => uint256) public packIndices; // total alpha scores staked uint256 public totalAlphaStaked = 0; // any rewards distributed when no wolves are staked uint256 public unaccountedRewards = 0; // amount of $SQUID due for each alpha point staked uint256 public squidPerAlpha = 0; // player earn 10000 $SQUID per day uint256 public constant DAILY_SQUID_RATE = 5000 ether; // player must have 2 days worth of $SQUID to unstake or else it's too cold uint256 public constant MINIMUM_TO_EXIT = 2 days; // wolves take a 20% tax on all $SQUID claimed uint256 public constant SQUID_CLAIM_TAX_PERCENTAGE = 20; // there will only ever be (roughly) 2.4 billion $SQUID earned through staking uint256 public constant MAXIMUM_GLOBAL_SQUID = 6000000000 ether; // amount of $SQUID earned so far uint256 public totalSquidEarned; // number of Player staked in the Arena uint256 public totalPlayerStaked; // the last time $SQUID was claimed uint256 public lastClaimTimestamp; // emergency rescue to allow unstaking without any checks but without $SQUID bool public rescueEnabled = false; /** * @param _squuid reference to the Squuid NFT contract * @param _squid reference to the $SQUID token */ constructor(address _squuid, address _squid) { squuid = Squuid(_squuid); squid = SQUID(_squid); } /** STAKING */ /** * adds Player and Wolves to the Arena and Pack * @param account the address of the staker * @param tokenIds the IDs of the Player and Wolves to stake */ function addManyToArenaAndPack(address account, uint16[] calldata tokenIds) external { require(account == _msgSender() || _msgSender() == address(squuid), "DONT GIVE YOUR TOKENS AWAY"); for (uint i = 0; i < tokenIds.length; i++) { if (_msgSender() != address(squuid)) { // dont do this step if its a mint + stake require(squuid.ownerOf(tokenIds[i]) == _msgSender(), "AINT YO TOKEN"); squuid.transferFrom(_msgSender(), address(this), tokenIds[i]); } else if (tokenIds[i] == 0) { continue; // there may be gaps in the array for stolen tokens } if (isPlayer(tokenIds[i])) _addPlayerToArena(account, tokenIds[i]); else _addGuardToPack(account, tokenIds[i]); } } /** * adds a single Player to the Arena * @param account the address of the staker * @param tokenId the ID of the Player to add to the Arena */ function _addPlayerToArena(address account, uint256 tokenId) internal whenNotPaused _updateEarnings { arena[tokenId] = Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(block.timestamp) }); totalPlayerStaked += 1; emit TokenStaked(account, tokenId, block.timestamp); } /** * adds a single Guard to the Pack * @param account the address of the staker * @param tokenId the ID of the Guard to add to the Pack */ function _addGuardToPack(address account, uint256 tokenId) internal { uint256 alpha = _alphaForGuard(tokenId); totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5 packIndices[tokenId] = pack[alpha].length; // Store the location of the guard in the Pack pack[alpha].push(Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(squidPerAlpha) })); // Add the guard to the Pack emit TokenStaked(account, tokenId, squidPerAlpha); } /** CLAIMING / UNSTAKING */ /** * realize $SQUID earnings and optionally unstake tokens from the Arena / Pack * to unstake a Player it will require it has 2 days worth of $SQUID unclaimed * @param tokenIds the IDs of the tokens to claim earnings from * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds */ function claimManyFromArenaAndPack(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings { uint256 owed = 0; for (uint i = 0; i < tokenIds.length; i++) { if (isPlayer(tokenIds[i])) owed += _claimPlayerFromArena(tokenIds[i], unstake); else owed += _claimGuardFromPack(tokenIds[i], unstake); } if (owed == 0) return; squid.mint(_msgSender(), owed); } /** * realize $SQUID earnings for a single Player and optionally unstake it * if not unstaking, pay a 20% tax to the staked Wolves * if unstaking, there is a 50% chance all $SQUID is stolen * @param tokenId the ID of the Player to claim earnings from * @param unstake whether or not to unstake the Player * @return owed - the amount of $SQUID earned */ function _claimPlayerFromArena(uint256 tokenId, bool unstake) internal returns (uint256 owed) { Stake memory stake = arena[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S SQUID"); if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) { owed = (block.timestamp - stake.value) * DAILY_SQUID_RATE / 1 days; } else if (stake.value > lastClaimTimestamp) { owed = 0; // $SQUID production stopped already } else { owed = (lastClaimTimestamp - stake.value) * DAILY_SQUID_RATE / 1 days; // stop earning additional $SQUID if it's all been earned } if (unstake) { if (random(tokenId) & 1 == 1) { // 50% chance of all $SQUID stolen _payGuardTax(owed); owed = 0; } delete arena[tokenId]; squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Player totalPlayerStaked -= 1; } else { _payGuardTax(owed * SQUID_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked wolves owed = owed * (100 - SQUID_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Player owner arena[tokenId] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(block.timestamp) }); // reset stake } emit PlayerClaimed(tokenId, owed, unstake); } /** * realize $SQUID earnings for a single Guard and optionally unstake it * Wolves earn $SQUID proportional to their Alpha rank * @param tokenId the ID of the Guard to claim earnings from * @param unstake whether or not to unstake the Guard * @return owed - the amount of $SQUID earned */ function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) { require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK"); uint256 alpha = _alphaForGuard(tokenId); Stake memory stake = pack[alpha][packIndices[tokenId]]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); owed = (alpha) * (squidPerAlpha - stake.value); // Calculate portion of tokens based on Alpha if (unstake) { totalAlphaStaked -= alpha; // Remove Alpha from total staked Stake memory lastStake = pack[alpha][pack[alpha].length - 1]; pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Guard to current position packIndices[lastStake.tokenId] = packIndices[tokenId]; pack[alpha].pop(); // Remove duplicate delete packIndices[tokenId]; // Delete old mapping squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Guard } else { pack[alpha][packIndices[tokenId]] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(squidPerAlpha) }); // reset stake } emit GuardClaimed(tokenId, owed, unstake); } /** * emergency unstake tokens * @param tokenIds the IDs of the tokens to claim earnings from */ function rescue(uint256[] calldata tokenIds) external { require(rescueEnabled, "RESCUE DISABLED"); uint256 tokenId; Stake memory stake; Stake memory lastStake; uint256 alpha; for (uint i = 0; i < tokenIds.length; i++) { tokenId = tokenIds[i]; if (isPlayer(tokenId)) { stake = arena[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); delete arena[tokenId]; squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Player totalPlayerStaked -= 1; emit PlayerClaimed(tokenId, 0, true); } else { alpha = _alphaForGuard(tokenId); stake = pack[alpha][packIndices[tokenId]]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); totalAlphaStaked -= alpha; // Remove Alpha from total staked lastStake = pack[alpha][pack[alpha].length - 1]; pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Guard to current position packIndices[lastStake.tokenId] = packIndices[tokenId]; pack[alpha].pop(); // Remove duplicate delete packIndices[tokenId]; // Delete old mapping squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Guard emit GuardClaimed(tokenId, 0, true); } } } /** ACCOUNTING */ /** * add $SQUID to claimable pot for the Pack * @param amount $SQUID to add to the pot */ function _payGuardTax(uint256 amount) internal { if (totalAlphaStaked == 0) { // if there's no staked wolves unaccountedRewards += amount; // keep track of $SQUID due to wolves return; } // makes sure to include any unaccounted $SQUID squidPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked; unaccountedRewards = 0; } /** * tracks $SQUID earnings to ensure it stops once 2.4 billion is eclipsed */ modifier _updateEarnings() { if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) { totalSquidEarned += (block.timestamp - lastClaimTimestamp) * totalPlayerStaked * DAILY_SQUID_RATE / 1 days; lastClaimTimestamp = block.timestamp; } _; } /** ADMIN */ /** * allows owner to enable "rescue mode" * simplifies accounting, prioritizes tokens out in emergency */ function setRescueEnabled(bool _enabled) external onlyOwner { rescueEnabled = _enabled; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } /** READ ONLY */ /** * checks if a token is a Player * @param tokenId the ID of the token to check * @return player - whether or not a token is a Player */ function isPlayer(uint256 tokenId) public view returns (bool player) { (player, , , , , , , , , ) = squuid.tokenTraits(tokenId); } /** * gets the alpha score for a Guard * @param tokenId the ID of the Guard to get the alpha score for * @return the alpha score of the Guard (5-8) */ function _alphaForGuard(uint256 tokenId) internal view returns (uint8) { ( , , , , , , , , , uint8 alphaIndex) = squuid.tokenTraits(tokenId); return MAX_ALPHA - alphaIndex; // alpha index is 0-3 } /** * chooses a random Guard thief when a newly minted token is stolen * @param seed a random value to choose a Guard from * @return the owner of the randomly selected Guard thief */ function randomGuardOwner(uint256 seed) external view returns (address) { if (totalAlphaStaked == 0) return address(0x0); uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; // choose a value from 0 to total alpha staked uint256 cumulative; seed >>= 32; // loop through each bucket of Wolves with the same alpha score for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { cumulative += pack[i].length * i; // if the value is not inside of that bucket, keep going if (bucket >= cumulative) continue; // get the address of a random Guard with that alpha score return pack[i][seed % pack[i].length].owner; } return address(0x0); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Arena directly"); return IERC721Receiver.onERC721Received.selector; } }
disables an address from minting / burning controller the address to disbale/
function removeController(address controller) external onlyOwner { controllers[controller] = false; }
98,504
import { RepayFacet } from "../RepayFacet.sol"; import { NFTLib } from "../../nft/libraries/NFTLib.sol"; import { LibLoans } from "../libraries/LibLoans.sol"; import { TellerNFT } from "../../nft/TellerNFT.sol"; contract MainnetRepayFacet is RepayFacet { constructor(address nftV2Address) RepayFacet(nftV2Address) {} /** * @notice On mainnet, we override the restakeNFT method so that TellerNFTV1 is also restakes * @param loanID ID of loan for which to restake linked NFT */ function _restakeNFTForRepayment(uint256 loanID) internal override { NFTLib.restakeLinked(loanID, LibLoans.loan(loanID).borrower); super._restakeNFTForRepayment(loanID); } /** * @notice On mainnet, we override the liquidateNFT method so that TellerNFTV1 is also transferred * @param loanID ID of loan for which to transfer linked NFT */ function _liquidateNFT(uint256 loanID) internal override { NFTLib.liquidateNFT(loanID); super._liquidateNFT(loanID); } }
On mainnet, we override the restakeNFT method so that TellerNFTV1 is also restakes loanID ID of loan for which to restake linked NFT/
function _restakeNFTForRepayment(uint256 loanID) internal override { NFTLib.restakeLinked(loanID, LibLoans.loan(loanID).borrower); super._restakeNFTForRepayment(loanID); }
12,651,007
/** *Submitted for verification at Etherscan.io on 2021-06-09 */ pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'UglyShiba' token contract // // Deployed to : 0xD445dC1f1d9ca1A5857adAE1FE1621cEE0744bc7 // Symbol : UGLYSHIB // Name : UglyShiba // Total supply: 1000000000000000 // Decimals : 18 // // https://t.me/UglyShiba // The ugly Shiba Inu fork- Please read our medium article before you buy! // https://uglyshib.medium.com/introducing-uglyshib-nfts-ec20244e67d0 // Ugly -but smart // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract UglyShiba is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function UglyShiba() public { symbol = "UGLYSHIB"; name = "UglyShiba"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[0xD445dC1f1d9ca1A5857adAE1FE1621cEE0744bc7] = _totalSupply; Transfer(address(0), 0xD445dC1f1d9ca1A5857adAE1FE1621cEE0744bc7, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint 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, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; 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, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, 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 constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
------------------------------------------------------------------------ Transfer the balance from token owner's account to to account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; }
7,959,968
// SPDX-License-Identifier: UNLICENSED // test pragma solidity ^0.8.0; import "./Profile.sol"; import "./Trace.sol"; contract ProductSC { // state management //1. Machine State for the product contract // 1 Activated = The participants can use functions in the product contract. // 0 Deactivated = The participants **cannot** use functions in the product contract. enum MachineState { Deactivated, Activated } MachineState private machineState; enum status { FARMING, MANUFACTURING, SHIPPING, RETAILING, PURCHASING, RECALLING } struct Product { uint256 productId; string productName; status statusType; uint256 productPrice; address FarmerId; address manufacturerId; address distributorId; address retailerId; address ConsumerId; } struct Farming { uint256 productId; uint256 recordBlock; uint256 farmingTime; uint256 harvestTime; string productLocation; } struct Manufacturing { uint256 productId; string processType; uint256 recordBlock; uint256 timestamp; } // relevant to track.sol, // may add new attribute after interact with tracker struct Logistics { uint256 productId; uint256 recordBlock; uint256 timeStamp; //To store sender and receiver addresses address sender; address receiver; } struct Retailing { uint256 productId; uint256 recordBlock; uint256 timeStamp; } struct Purchasing { uint256 productId; uint256 recordBlock; uint256 timeStamp; } // Event for the current product status event CurrentProductStatus(uint256 productId, uint256 productStatus); // maaping parts mapping(uint256 => Product) public products; mapping(uint256 => Farming) public farming_process; mapping(uint256 => Manufacturing) public manu_process; mapping(uint256 => Logistics) public logi_process; mapping(uint256 => Retailing) public retail_process; mapping(uint256 => Purchasing) public purchase_process; uint256 public numProducts = 0; address public traceAddress; Profile profile; address public regulatorAddress; constructor(address _traceAddress, address _profileAddress) { traceAddress = _traceAddress; profile = Profile(_profileAddress); //add regulator address regulatorAddress = profile.getRegulatorAddress(); //initial machine state machineState = MachineState.Deactivated; } //1. For Farming process (The first node of one-line supply chain) function createProduct( string memory name, uint256 _farmtime, uint256 _harvtime, string memory _productLocation ) public isFarmerOnly onlyActivatedMachineState returns (uint256) { require( _harvtime > _farmtime, "Harvest time should be later than farm time." ); numProducts = numProducts + 1; Product memory p; p.productName = name; p.productId = numProducts; p.statusType = status.FARMING; p.FarmerId = msg.sender; products[p.productId] = p; Farming memory f; f.productId = p.productId; f.farmingTime = _farmtime; f.harvestTime = _harvtime; f.recordBlock = block.number; f.productLocation = _productLocation; farming_process[p.productId] = f; emit CurrentProductStatus(f.productId, uint256(p.statusType)); return numProducts; } //2. For MANUFACTURING process (The second node of one-line supply chain) function manuProductInfo(uint256 _pid, string memory _processtype) public isManufacturerOnly isProductActive(_pid) isProductIdExist(_pid) onlyActivatedMachineState { require( products[_pid].statusType == status.FARMING, "The current status of product should be FARMING." ); Product storage existProduct = products[_pid]; existProduct.manufacturerId = msg.sender; existProduct.statusType = status.MANUFACTURING; Manufacturing memory m; m.productId = _pid; m.processType = _processtype; m.recordBlock = block.number; m.timestamp = block.timestamp; manu_process[_pid] = m; emit CurrentProductStatus( m.productId, uint256(existProduct.statusType) ); } //3. For Logistic process (The third node of one-line supply chain) //**Scope** Manufacturer sends the product to the chosen Logistic or Oracle. // Valiadation // 1. msg.sender account type = manufacturer // 2. receiver = retailerId // 3. logistic = logistic or oracle function sendProduct( uint256 _pid, address receiver, address logistic, string memory trackingNumber ) public isProductIdExist(_pid) OnlyProductReadyToSend(_pid) isManufacturerOnly onlyActivatedMachineState { require( profile.isLogisticOrOracle(logistic) == true, "It is not the logistic address." ); require( profile.isRetailer(receiver) == true, "The receiver is not the retailer address." ); require( products[_pid].statusType == status.MANUFACTURING, "The current status of product should be MANUFACTURING." ); require( bytes(trackingNumber).length != 0, "The tracking number cannot be empty." ); Product storage existProduct = products[_pid]; existProduct.distributorId = msg.sender; existProduct.statusType = status.SHIPPING; Logistics memory l; l.productId = _pid; l.recordBlock = block.number; l.timeStamp = block.timestamp; l.sender = msg.sender; l.receiver = receiver; logi_process[_pid] = l; Trace trace = Trace(traceAddress); // set product contract address //trace.setProductContractAddress(address(this)); trace.addProduct(_pid, logistic, trackingNumber); emit CurrentProductStatus( l.productId, uint256(existProduct.statusType) ); } //4. For Retailing process (The fourth node of one-line supply chain) function retailProductInfo(uint256 _pid) public isRetailerOnly isProductActive(_pid) isProductIdExist(_pid) onlyActivatedMachineState { Product storage existProduct = products[_pid]; existProduct.retailerId = msg.sender; existProduct.statusType = status.RETAILING; Retailing memory r; r.productId = _pid; r.recordBlock = block.number; r.timeStamp = block.timestamp; retail_process[_pid] = r; emit CurrentProductStatus( r.productId, uint256(existProduct.statusType) ); } //5. For Purchasing process (The last node of one-line supply chain) function purchasingProductInfo(uint256 _pid, uint256 _price) public isConsumerOnly isProductActive(_pid) isProductIdExist(_pid) onlyActivatedMachineState { require( products[_pid].statusType == status.RETAILING, "The current status of product should be RETAILING." ); Product storage existProduct = products[_pid]; existProduct.ConsumerId = msg.sender; existProduct.statusType = status.PURCHASING; existProduct.productPrice = _price; Purchasing memory p; p.productId = _pid; p.recordBlock = block.number; p.timeStamp = block.timestamp; purchase_process[_pid] = p; emit CurrentProductStatus( p.productId, uint256(existProduct.statusType) ); } //event event RecallProduct(uint256 productId); //Validation // 1. the sender must be Farmer; manufacturer; distributor; retailer; Consumer in this product // 2. The product status is not RECALLING function recallProduct(uint256 productId) public isProductActive(productId) isProductIdExist(productId) onlyActivatedMachineState { require( msg.sender == products[productId].FarmerId || msg.sender == products[productId].manufacturerId || msg.sender == products[productId].distributorId || msg.sender == products[productId].retailerId || msg.sender == products[productId].ConsumerId, "The address is not farmer,manufacturer, distributor, retailer or consumer in this product." ); products[productId].statusType = status.RECALLING; emit RecallProduct(productId); } // private functions // Does account address exist? function isProductReadyToSend(uint256 productId) private view onlyActivatedMachineState returns (bool) { if (products[productId].statusType == status.MANUFACTURING) { return true; } return false; } function getMachineState() public view returns (uint256) { uint256 _machineState = uint256(machineState); return _machineState; } /// @notice Activate contract function setActivatedMachineState() public onlyRegulator returns (uint256) { //Validation // The profile contract must be active. require( profile.getMachineState() == 1, "The profile contract must be active before activate the product contract." ); // Activate profile contract machineState = MachineState.Activated; return uint256(machineState); } /// @notice Deactivate contract function setDeactivatedMachineState() public onlyRegulator returns (uint256) { // Deactivate profile contract machineState = MachineState.Deactivated; return uint256(machineState); } /// @notice Destroy Profile Contract function destroyContract() public payable onlyRegulator { // Deactivate contract machineState = MachineState.Deactivated; address payable regulator_address = payable(address(regulatorAddress)); selfdestruct(regulator_address); } event ShowOneLineTrack( address FarmerId, address manufacturerId, address distributorId, address retailerId, address ConsumerId, uint256 statusType ); function showOneLineTrack(uint256 _productId) public isProductIdExist(_productId) { Product storage existProduct = products[_productId]; //empty address : 0x0000000000000000000000000000000000000000 emit ShowOneLineTrack( existProduct.FarmerId, existProduct.manufacturerId, existProduct.distributorId, existProduct.retailerId, existProduct.ConsumerId, uint256(existProduct.statusType) ); } // Validation parts // modifiers modifier onlyRegulator { require( msg.sender == regulatorAddress, "This function can only be executed by the regulator." ); _; } modifier OnlyProductReadyToSend(uint256 _productId) { require( isProductReadyToSend(_productId) == true, "Cannot send this product. Because the product is not ready to send or it has already been sent." ); _; } modifier isFarmerOnly { require( profile.isFarmer(msg.sender) == true, "This function can only be executed by the farmer." ); _; } modifier isManufacturerOnly { require( profile.isManufacturer(msg.sender) == true, "This function can only be executed by the manufacturer." ); _; } modifier isLogisticOrOracleOnly { require( profile.isLogisticOrOracle(msg.sender) == true, "This function can only be executed by the logistic or oracle." ); _; } modifier isRetailerOnly { require( profile.isRetailer(msg.sender) == true, "This function can only be executed by the retailer." ); _; } modifier isConsumerOnly { require( profile.isConsumer(msg.sender) == true, "This function can only be executed by the consumer." ); _; } modifier isProductActive(uint256 _productId) { require( products[_productId].statusType != status.RECALLING, "This product has already recalled." ); _; } modifier isProductIdExist(uint256 __productId) { require( products[__productId].productId != 0, "This product id does not exist." ); _; } modifier onlyActivatedMachineState { require( machineState == MachineState.Activated, "This contract is not activated by the regulator." ); _; } }
Destroy Profile Contract Deactivate contract
function destroyContract() public payable onlyRegulator { machineState = MachineState.Deactivated; address payable regulator_address = payable(address(regulatorAddress)); selfdestruct(regulator_address); } event ShowOneLineTrack( address FarmerId, address manufacturerId, address distributorId, address retailerId, address ConsumerId, uint256 statusType );
6,447,215
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./HoldefiPausableOwnable.sol"; import "./HoldefiCollaterals.sol"; /// @notice File: contracts/HoldefiPrices.sol interface HoldefiPricesInterface { function getAssetValueFromAmount(address asset, uint256 amount) external view returns(uint256 value); function getAssetAmountFromValue(address asset, uint256 value) external view returns(uint256 amount); } /// @notice File: contracts/HoldefiSettings.sol interface HoldefiSettingsInterface { /// @notice Markets Features struct MarketSettings { bool isExist; bool isActive; uint256 borrowRate; uint256 borrowRateUpdateTime; uint256 suppliersShareRate; uint256 suppliersShareRateUpdateTime; uint256 promotionRate; } /// @notice Collateral Features struct CollateralSettings { bool isExist; bool isActive; uint256 valueToLoanRate; uint256 VTLUpdateTime; uint256 penaltyRate; uint256 penaltyUpdateTime; uint256 bonusRate; } function getInterests(address market) external view returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate); function resetPromotionRate (address market) external; function getMarketsList() external view returns(address[] memory marketsList); function marketAssets(address market) external view returns(MarketSettings memory); function collateralAssets(address collateral) external view returns(CollateralSettings memory); } /// @title Main Holdefi contract /// @author Holdefi Team /// @dev The address of ETH considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE /// @dev All indexes are scaled by (secondsPerYear * rateDecimals) /// @dev All values are based ETH price considered 1 and all values decimals considered 30 contract Holdefi is HoldefiPausableOwnable { using SafeMath for uint256; /// @notice Markets are assets can be supplied and borrowed struct Market { uint256 totalSupply; uint256 supplyIndex; // Scaled by: secondsPerYear * rateDecimals uint256 supplyIndexUpdateTime; uint256 totalBorrow; uint256 borrowIndex; // Scaled by: secondsPerYear * rateDecimals uint256 borrowIndexUpdateTime; uint256 promotionReserveScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionReserveLastUpdateTime; uint256 promotionDebtScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionDebtLastUpdateTime; } /// @notice Collaterals are assets can be used only as collateral for borrowing with no interest struct Collateral { uint256 totalCollateral; uint256 totalLiquidatedCollateral; } /// @notice Users profile for each market struct MarketAccount { mapping (address => uint) allowance; uint256 balance; uint256 accumulatedInterest; uint256 lastInterestIndex; // Scaled by: secondsPerYear * rateDecimals } /// @notice Users profile for each collateral struct CollateralAccount { mapping (address => uint) allowance; uint256 balance; uint256 lastUpdateTime; } struct MarketData { uint256 balance; uint256 interest; uint256 currentIndex; } address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice All rates in this contract are scaled by rateDecimals uint256 constant public rateDecimals = 10 ** 4; uint256 constant public secondsPerYear = 31536000; /// @dev For round up borrow interests uint256 constant private oneUnit = 1; /// @dev Used for calculating liquidation threshold /// @dev There is 5% gap between value to loan rate and liquidation rate uint256 constant private fivePercentLiquidationGap = 500; /// @notice Contract for getting protocol settings HoldefiSettingsInterface public holdefiSettings; /// @notice Contract for getting asset prices HoldefiPricesInterface public holdefiPrices; /// @notice Contract for holding collaterals HoldefiCollaterals public holdefiCollaterals; /// @dev Markets: marketAddress => marketDetails mapping (address => Market) public marketAssets; /// @dev Collaterals: collateralAddress => collateralDetails mapping (address => Collateral) public collateralAssets; /// @dev Markets Debt after liquidation: collateralAddress => marketAddress => marketDebtBalance mapping (address => mapping (address => uint)) public marketDebt; /// @dev Users Supplies: userAddress => marketAddress => supplyDetails mapping (address => mapping (address => MarketAccount)) private supplies; /// @dev Users Borrows: userAddress => collateralAddress => marketAddress => borrowDetails mapping (address => mapping (address => mapping (address => MarketAccount))) private borrows; /// @dev Users Collaterals: userAddress => collateralAddress => collateralDetails mapping (address => mapping (address => CollateralAccount)) private collaterals; // ----------- Events ----------- /// @notice Event emitted when a market asset is supplied event Supply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a supply is withdrawn event WithdrawSupply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when a collateral asset is deposited event Collateralize( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a collateral is withdrawn event WithdrawCollateral( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a market asset is borrowed event Borrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a borrow is repaid event RepayBorrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when the supply index is updated for a market asset event UpdateSupplyIndex(address indexed market, uint256 newSupplyIndex, uint256 supplyRate); /// @notice Event emitted when the borrow index is updated for a market asset event UpdateBorrowIndex(address indexed market, uint256 newBorrowIndex); /// @notice Event emitted when a collateral is liquidated event CollateralLiquidated( address indexed borrower, address indexed market, address indexed collateral, uint256 marketDebt, uint256 liquidatedCollateral ); /// @notice Event emitted when a liquidated collateral is purchased in exchange for the specified market event BuyLiquidatedCollateral( address indexed market, address indexed collateral, uint256 marketAmount, uint256 collateralAmount ); /// @notice Event emitted when HoldefiPrices contract is changed event HoldefiPricesContractChanged(address newAddress, address oldAddress); /// @notice Event emitted when a liquidation reserve is withdrawn by the owner event LiquidationReserveWithdrawn(address indexed collateral, uint256 amount); /// @notice Event emitted when a liquidation reserve is deposited event LiquidationReserveDeposited(address indexed collateral, uint256 amount); /// @notice Event emitted when a promotion reserve is withdrawn by the owner event PromotionReserveWithdrawn(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is deposited event PromotionReserveDeposited(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is updated event PromotionReserveUpdated(address indexed market, uint256 promotionReserve); /// @notice Event emitted when a promotion debt is updated event PromotionDebtUpdated(address indexed market, uint256 promotionDebt); /// @notice Initializes the Holdefi contract /// @param holdefiSettingsAddress Holdefi settings contract address /// @param holdefiPricesAddress Holdefi prices contract address constructor( HoldefiSettingsInterface holdefiSettingsAddress, HoldefiPricesInterface holdefiPricesAddress ) public { holdefiSettings = holdefiSettingsAddress; holdefiPrices = holdefiPricesAddress; holdefiCollaterals = new HoldefiCollaterals(); } /// @dev Modifier to check if the asset is ETH or not /// @param asset Address of the given asset modifier isNotETHAddress(address asset) { require (asset != ethAddress, "Asset should not be ETH address"); _; } /// @dev Modifier to check if the market is active or not /// @param market Address of the given market modifier marketIsActive(address market) { require (holdefiSettings.marketAssets(market).isActive, "Market is not active"); _; } /// @dev Modifier to check if the collateral is active or not /// @param collateral Address of the given collateral modifier collateralIsActive(address collateral) { require (holdefiSettings.collateralAssets(collateral).isActive, "Collateral is not active"); _; } /// @dev Modifier to check if the account address is equal to the msg.sender or not /// @param account The given account address modifier accountIsValid(address account) { require (msg.sender != account, "Account is not valid"); _; } receive() external payable { revert(); } /// @notice Returns balance and interest of an account for a given market /// @dev supplyInterest = accumulatedInterest + (balance * (marketSupplyIndex - userLastSupplyInterestIndex)) /// @param account Supplier address to get supply information /// @param market Address of the given market /// @return balance Supplied amount on the specified market /// @return interest Profit earned /// @return currentSupplyIndex Supply index for the given market at current time function getAccountSupply(address account, address market) public view returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex) { balance = supplies[account][market].balance; (currentSupplyIndex,,) = getCurrentSupplyIndex(market); uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); interest = supplies[account][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns balance and interest of an account for a given market on a given collateral /// @dev borrowInterest = accumulatedInterest + (balance * (marketBorrowIndex - userLastBorrowInterestIndex)) /// @param account Borrower address to get Borrow information /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return balance Borrowed amount on the specified market /// @return interest The amount of interest the borrower should pay /// @return currentBorrowIndex Borrow index for the given market at current time function getAccountBorrow(address account, address market, address collateral) public view returns (uint256 balance, uint256 interest, uint256 currentBorrowIndex) { balance = borrows[account][collateral][market].balance; (currentBorrowIndex,,) = getCurrentBorrowIndex(market); uint256 deltaInterestIndex = currentBorrowIndex.sub(borrows[account][collateral][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); if (balance > 0) { deltaInterest = deltaInterest.add(oneUnit); } interest = borrows[account][collateral][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns collateral balance, time since last activity, borrow power, total borrow value, and liquidation status for a given collateral /// @dev borrowPower = (collateralValue / collateralValueToLoanRate) - totalBorrowValue /// @dev liquidationThreshold = collateralValueToLoanRate - 5% /// @dev User will be in liquidation state if (collateralValue / totalBorrowValue) < liquidationThreshold /// @param account Account address to get collateral information /// @param collateral Address of the given collateral /// @return balance Amount of the specified collateral /// @return timeSinceLastActivity Time since last activity performed by the account /// @return borrowPowerValue The borrowing power for the account of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral /// @return underCollateral A boolean value indicates whether the user is in the liquidation state or not function getAccountCollateral(address account, address collateral) public view returns ( uint256 balance, uint256 timeSinceLastActivity, uint256 borrowPowerValue, uint256 totalBorrowValue, bool underCollateral ) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; if (valueToLoanRate == 0) { return (0, 0, 0, 0, false); } balance = collaterals[account][collateral].balance; uint256 collateralValue = holdefiPrices.getAssetValueFromAmount(collateral, balance); uint256 liquidationThresholdRate = valueToLoanRate.sub(fivePercentLiquidationGap); uint256 totalBorrowPowerValue = collateralValue.mul(rateDecimals).div(valueToLoanRate); uint256 liquidationThresholdValue = collateralValue.mul(rateDecimals).div(liquidationThresholdRate); totalBorrowValue = getAccountTotalBorrowValue(account, collateral); if (totalBorrowValue > 0) { timeSinceLastActivity = block.timestamp.sub(collaterals[account][collateral].lastUpdateTime); } borrowPowerValue = 0; if (totalBorrowValue < totalBorrowPowerValue) { borrowPowerValue = totalBorrowPowerValue.sub(totalBorrowValue); } underCollateral = false; if (totalBorrowValue > liquidationThresholdValue) { underCollateral = true; } } /// @notice Returns maximum amount spender can withdraw from account supplies on a given market /// @param account Supplier address /// @param spender Spender address /// @param market Address of the given market /// @return res Maximum amount spender can withdraw from account supplies on a given market function getAccountWithdrawSupplyAllowance (address account, address spender, address market) external view returns (uint256 res) { res = supplies[account][market].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account balance on a given collateral /// @param account Account address /// @param spender Spender address /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account balance on a given collateral function getAccountWithdrawCollateralAllowance ( address account, address spender, address collateral ) external view returns (uint256 res) { res = collaterals[account][collateral].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account borrows on a given market based on a given collteral /// @param account Borrower address /// @param spender Spender address /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account borrows on a given market based on a given collteral function getAccountBorrowAllowance ( address account, address spender, address market, address collateral ) external view returns (uint256 res) { res = borrows[account][collateral][market].allowance[spender]; } /// @notice Returns total borrow value of an account based on a given collateral /// @param account Account address /// @param collateral Address of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral function getAccountTotalBorrowValue (address account, address collateral) public view returns (uint256 totalBorrowValue) { MarketData memory borrowData; address market; uint256 totalDebt; uint256 assetValue; totalBorrowValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; (borrowData.balance, borrowData.interest,) = getAccountBorrow(account, market, collateral); totalDebt = borrowData.balance.add(borrowData.interest); assetValue = holdefiPrices.getAssetValueFromAmount(market, totalDebt); totalBorrowValue = totalBorrowValue.add(assetValue); } } /// @notice The collateral reserve amount for buying liquidated collateral /// @param collateral Address of the given collateral /// @return reserve Liquidation reserves for the given collateral function getLiquidationReserve (address collateral) public view returns(uint256 reserve) { address market; uint256 assetValue; uint256 totalDebtValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; assetValue = holdefiPrices.getAssetValueFromAmount(market, marketDebt[collateral][market]); totalDebtValue = totalDebtValue.add(assetValue); } uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 totalDebtCollateralValue = totalDebtValue.mul(bonusRate).div(rateDecimals); uint256 liquidatedCollateralNeeded = holdefiPrices.getAssetAmountFromValue( collateral, totalDebtCollateralValue ); reserve = 0; uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; if (totalLiquidatedCollateral > liquidatedCollateralNeeded) { reserve = totalLiquidatedCollateral.sub(liquidatedCollateralNeeded); } } /// @notice Returns the amount of discounted collateral can be bought in exchange for the amount of a given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param marketAmount The amount of market should be paid /// @return collateralAmountWithDiscount Amount of discounted collateral can be bought function getDiscountedCollateralAmount (address market, address collateral, uint256 marketAmount) public view returns (uint256 collateralAmountWithDiscount) { uint256 marketValue = holdefiPrices.getAssetValueFromAmount(market, marketAmount); uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 collateralValue = marketValue.mul(bonusRate).div(rateDecimals); collateralAmountWithDiscount = holdefiPrices.getAssetAmountFromValue(collateral, collateralValue); } /// @notice Returns supply index and supply rate for a given market at current time /// @dev newSupplyIndex = oldSupplyIndex + (deltaTime * supplyRate) /// @param market Address of the given market /// @return supplyIndex Supply index of the given market /// @return supplyRate Supply rate of the given market /// @return currentTime Current block timestamp function getCurrentSupplyIndex (address market) public view returns ( uint256 supplyIndex, uint256 supplyRate, uint256 currentTime ) { (, uint256 supplyRateBase, uint256 promotionRate) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 deltaTimeSupply = currentTime.sub(marketAssets[market].supplyIndexUpdateTime); supplyRate = supplyRateBase.add(promotionRate); uint256 deltaTimeInterest = deltaTimeSupply.mul(supplyRate); supplyIndex = marketAssets[market].supplyIndex.add(deltaTimeInterest); } /// @notice Returns borrow index and borrow rate for the given market at current time /// @dev newBorrowIndex = oldBorrowIndex + (deltaTime * borrowRate) /// @param market Address of the given market /// @return borrowIndex Borrow index of the given market /// @return borrowRate Borrow rate of the given market /// @return currentTime Current block timestamp function getCurrentBorrowIndex (address market) public view returns ( uint256 borrowIndex, uint256 borrowRate, uint256 currentTime ) { borrowRate = holdefiSettings.marketAssets(market).borrowRate; currentTime = block.timestamp; uint256 deltaTimeBorrow = currentTime.sub(marketAssets[market].borrowIndexUpdateTime); uint256 deltaTimeInterest = deltaTimeBorrow.mul(borrowRate); borrowIndex = marketAssets[market].borrowIndex.add(deltaTimeInterest); } /// @notice Returns promotion reserve for a given market at current time /// @dev promotionReserveScaled is scaled by (secondsPerYear * rateDecimals) /// @param market Address of the given market /// @return promotionReserveScaled Promotion reserve of the given market /// @return currentTime Current block timestamp function getPromotionReserve (address market) public view returns (uint256 promotionReserveScaled, uint256 currentTime) { (uint256 borrowRate, uint256 supplyRateBase,) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 allSupplyInterest = marketAssets[market].totalSupply.mul(supplyRateBase); uint256 allBorrowInterest = marketAssets[market].totalBorrow.mul(borrowRate); uint256 deltaTime = currentTime.sub(marketAssets[market].promotionReserveLastUpdateTime); uint256 currentInterest = allBorrowInterest.sub(allSupplyInterest); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(deltaTimeInterest); } /// @notice Returns promotion debt for a given market at current time /// @dev promotionDebtScaled is scaled by secondsPerYear * rateDecimals /// @param market Address of the given market /// @return promotionDebtScaled Promotion debt of the given market /// @return currentTime Current block timestamp function getPromotionDebt (address market) public view returns (uint256 promotionDebtScaled, uint256 currentTime) { uint256 promotionRate = holdefiSettings.marketAssets(market).promotionRate; currentTime = block.timestamp; promotionDebtScaled = marketAssets[market].promotionDebtScaled; if (promotionRate != 0) { uint256 deltaTime = block.timestamp.sub(marketAssets[market].promotionDebtLastUpdateTime); uint256 currentInterest = marketAssets[market].totalSupply.mul(promotionRate); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionDebtScaled = promotionDebtScaled.add(deltaTimeInterest); } } /// @notice Update a market supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeSupplyRate (address market) public { updateSupplyIndex(market); updatePromotionReserve(market); updatePromotionDebt(market); } /// @notice Update a market borrow index, supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeBorrowRate (address market) external { updateBorrowIndex(market); beforeChangeSupplyRate(market); } /// @notice Deposit ERC20 asset for supplying /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(msg.sender, market, amount, referralCode); } /// @notice Deposit ETH for supplying /// @notice msg.value The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(uint16 referralCode) external payable { supplyInternal(msg.sender, ethAddress, msg.value, referralCode); } /// @notice Sender deposits ERC20 asset belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(account, market, amount, referralCode); } /// @notice Sender deposits ETH belonging to the supplier /// @notice msg.value The amount of ETH sender deposits belonging to the supplier /// @param account Address of the supplier /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, uint16 referralCode) external payable { supplyInternal(account, ethAddress, msg.value, referralCode); } /// @notice Sender approves of the withdarawl for the account in the market asset /// @param account Address of the account allowed to withdrawn /// @param market Address of the given market /// @param amount The amount is allowed to withdrawn function approveWithdrawSupply(address account, address market, uint256 amount) external accountIsValid(account) marketIsActive(market) { supplies[msg.sender][market].allowance[account] = amount; } /// @notice Withdraw supply of a given market /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupply(address market, uint256 amount) external { withdrawSupplyInternal(msg.sender, market, amount); } /// @notice Sender withdraws supply belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupplyBehalf(address account, address market, uint256 amount) external { uint256 allowance = supplies[account][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); supplies[account][market].allowance[msg.sender] = allowance.sub(amount); withdrawSupplyInternal(account, market, amount); } /// @notice Deposit ERC20 asset as a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralize (address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(msg.sender, collateral, amount); } /// @notice Deposit ETH as a collateral /// @notice msg.value The amount of ETH will be collateralized function collateralize () external payable { collateralizeInternal(msg.sender, ethAddress, msg.value); } /// @notice Sender deposits ERC20 asset as a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralizeBehalf (address account, address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(account, collateral, amount); } /// @notice Sender deposits ETH as a collateral belonging to the user /// @notice msg.value The amount of ETH Sender deposits as a collateral belonging to the user /// @param account Address of the user function collateralizeBehalf (address account) external payable { collateralizeInternal(account, ethAddress, msg.value); } /// @notice Sender approves the account to withdraw the collateral /// @param account Address is allowed to withdraw the collateral /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveWithdrawCollateral (address account, address collateral, uint256 amount) external accountIsValid(account) collateralIsActive(collateral) { collaterals[msg.sender][collateral].allowance[account] = amount; } /// @notice Withdraw a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateral (address collateral, uint256 amount) external { withdrawCollateralInternal(msg.sender, collateral, amount); } /// @notice Sender withdraws a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateralBehalf (address account, address collateral, uint256 amount) external { uint256 allowance = collaterals[account][collateral].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); collaterals[account][collateral].allowance[msg.sender] = allowance.sub(amount); withdrawCollateralInternal(account, collateral, amount); } /// @notice Sender approves the account to borrow a given market based on given collateral /// @param account Address that is allowed to borrow the given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveBorrow (address account, address market, address collateral, uint256 amount) external accountIsValid(account) marketIsActive(market) { borrows[msg.sender][collateral][market].allowance[account] = amount; } /// @notice Borrow an asset /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the given market will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrow (address market, address collateral, uint256 amount, uint16 referralCode) external { borrowInternal(msg.sender, market, collateral, amount, referralCode); } /// @notice Sender borrows an asset belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrowBehalf (address account, address market, address collateral, uint256 amount, uint16 referralCode) external { uint256 allowance = borrows[account][collateral][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); borrows[account][collateral][market].allowance[msg.sender] = allowance.sub(amount); borrowInternal(account, market, collateral, amount, referralCode); } /// @notice Repay an ERC20 asset based on a given collateral /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be Repaid function repayBorrow (address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(msg.sender, market, collateral, amount); } /// @notice Repay an ETH based on a given collateral /// @notice msg.value The amount of ETH will be repaid /// @param collateral Address of the given collateral function repayBorrow (address collateral) external payable { repayBorrowInternal(msg.sender, ethAddress, collateral, msg.value); } /// @notice Sender repays an ERC20 asset based on a given collateral belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be repaid function repayBorrowBehalf (address account, address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(account, market, collateral, amount); } /// @notice Sender repays an ETH based on a given collateral belonging to the borrower /// @notice msg.value The amount of ETH sender repays belonging to the borrower /// @param account Address of the borrower /// @param collateral Address of the given collateral function repayBorrowBehalf (address account, address collateral) external payable { repayBorrowInternal(account, ethAddress, collateral, msg.value); } /// @notice Liquidate borrower's collateral /// @param borrower Address of the borrower who should be liquidated /// @param market Address of the given market /// @param collateral Address of the given collateral function liquidateBorrowerCollateral (address borrower, address market, address collateral) external whenNotPaused("liquidateBorrowerCollateral") { MarketData memory borrowData; (borrowData.balance, borrowData.interest,) = getAccountBorrow(borrower, market, collateral); require(borrowData.balance > 0, "User should have debt"); (uint256 collateralBalance, uint256 timeSinceLastActivity,,, bool underCollateral) = getAccountCollateral(borrower, collateral); require (underCollateral || (timeSinceLastActivity > secondsPerYear), "User should be under collateral or time is over" ); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); uint256 totalBorrowedBalanceValue = holdefiPrices.getAssetValueFromAmount(market, totalBorrowedBalance); uint256 liquidatedCollateralValue = totalBorrowedBalanceValue .mul(holdefiSettings.collateralAssets(collateral).penaltyRate) .div(rateDecimals); uint256 liquidatedCollateral = holdefiPrices.getAssetAmountFromValue(collateral, liquidatedCollateralValue); if (liquidatedCollateral > collateralBalance) { liquidatedCollateral = collateralBalance; } collaterals[borrower][collateral].balance = collateralBalance.sub(liquidatedCollateral); collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(liquidatedCollateral); collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.add(liquidatedCollateral); delete borrows[borrower][collateral][market]; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(borrowData.balance); marketDebt[collateral][market] = marketDebt[collateral][market].add(totalBorrowedBalance); emit CollateralLiquidated(borrower, market, collateral, totalBorrowedBalance, liquidatedCollateral); } /// @notice Buy collateral in exchange for ERC20 asset /// @param market Address of the market asset should be paid to buy collateral /// @param collateral Address of the liquidated collateral /// @param marketAmount The amount of the given market will be paid function buyLiquidatedCollateral (address market, address collateral, uint256 marketAmount) external isNotETHAddress(market) { buyLiquidatedCollateralInternal(market, collateral, marketAmount); } /// @notice Buy collateral in exchange for ETH /// @notice msg.value The amount of the given market that will be paid /// @param collateral Address of the liquidated collateral function buyLiquidatedCollateral (address collateral) external payable { buyLiquidatedCollateralInternal(ethAddress, collateral, msg.value); } /// @notice Deposit ERC20 asset as liquidation reserve /// @param collateral Address of the given collateral /// @param amount The amount that will be deposited function depositLiquidationReserve(address collateral, uint256 amount) external isNotETHAddress(collateral) { depositLiquidationReserveInternal(collateral, amount); } /// @notice Deposit ETH asset as liquidation reserve /// @notice msg.value The amount of ETH that will be deposited function depositLiquidationReserve() external payable { depositLiquidationReserveInternal(ethAddress, msg.value); } /// @notice Withdraw liquidation reserve only by the owner /// @param collateral Address of the given collateral /// @param amount The amount that will be withdrawn function withdrawLiquidationReserve (address collateral, uint256 amount) external onlyOwner { uint256 maxWithdraw = getLiquidationReserve(collateral); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit LiquidationReserveWithdrawn(collateral, amount); } /// @notice Deposit ERC20 asset as promotion reserve /// @param market Address of the given market /// @param amount The amount that will be deposited function depositPromotionReserve (address market, uint256 amount) external isNotETHAddress(market) { depositPromotionReserveInternal(market, amount); } /// @notice Deposit ETH as promotion reserve /// @notice msg.value The amount of ETH that will be deposited function depositPromotionReserve () external payable { depositPromotionReserveInternal(ethAddress, msg.value); } /// @notice Withdraw promotion reserve only by the owner /// @param market Address of the given market /// @param amount The amount that will be withdrawn function withdrawPromotionReserve (address market, uint256 amount) external onlyOwner { (uint256 reserveScaled,) = getPromotionReserve(market); (uint256 debtScaled,) = getPromotionDebt(market); uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); uint256 increasedDebtScaled = amountScaled.add(debtScaled); require (reserveScaled > increasedDebtScaled, "Amount should be less than max"); marketAssets[market].promotionReserveScaled = reserveScaled.sub(amountScaled); transferFromHoldefi(msg.sender, market, amount); emit PromotionReserveWithdrawn(market, amount); } /// @notice Set Holdefi prices contract only by the owner /// @param newHoldefiPrices Address of the new Holdefi prices contract function setHoldefiPricesContract (HoldefiPricesInterface newHoldefiPrices) external onlyOwner { emit HoldefiPricesContractChanged(address(newHoldefiPrices), address(holdefiPrices)); holdefiPrices = newHoldefiPrices; } /// @notice Promotion reserve and debt settlement /// @param market Address of the given market function reserveSettlement (address market) external { require(msg.sender == address(holdefiSettings), "Sender should be Holdefi Settings contract"); uint256 promotionReserve = marketAssets[market].promotionReserveScaled; uint256 promotionDebt = marketAssets[market].promotionDebtScaled; require(promotionReserve > promotionDebt, "Not enough promotion reserve"); promotionReserve = promotionReserve.sub(promotionDebt); marketAssets[market].promotionReserveScaled = promotionReserve; marketAssets[market].promotionDebtScaled = 0; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, promotionReserve); emit PromotionDebtUpdated(market, 0); } /// @notice Update supply index of a market /// @param market Address of the given market function updateSupplyIndex (address market) internal { (uint256 currentSupplyIndex, uint256 supplyRate, uint256 currentTime) = getCurrentSupplyIndex(market); marketAssets[market].supplyIndex = currentSupplyIndex; marketAssets[market].supplyIndexUpdateTime = currentTime; emit UpdateSupplyIndex(market, currentSupplyIndex, supplyRate); } /// @notice Update borrow index of a market /// @param market Address of the given market function updateBorrowIndex (address market) internal { (uint256 currentBorrowIndex,, uint256 currentTime) = getCurrentBorrowIndex(market); marketAssets[market].borrowIndex = currentBorrowIndex; marketAssets[market].borrowIndexUpdateTime = currentTime; emit UpdateBorrowIndex(market, currentBorrowIndex); } /// @notice Update promotion reserve of a market /// @param market Address of the given market function updatePromotionReserve(address market) internal { (uint256 reserveScaled,) = getPromotionReserve(market); marketAssets[market].promotionReserveScaled = reserveScaled; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, reserveScaled); } /// @notice Update promotion debt of a market /// @dev Promotion rate will be set to 0 if (promotionDebt >= promotionReserve) /// @param market Address of the given market function updatePromotionDebt(address market) internal { (uint256 debtScaled,) = getPromotionDebt(market); if (marketAssets[market].promotionDebtScaled != debtScaled){ marketAssets[market].promotionDebtScaled = debtScaled; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionDebtUpdated(market, debtScaled); } if (marketAssets[market].promotionReserveScaled <= debtScaled) { holdefiSettings.resetPromotionRate(market); } } /// @notice transfer ETH or ERC20 asset from this contract function transferFromHoldefi(address receiver, address asset, uint256 amount) internal { bool success = false; if (asset == ethAddress){ (success, ) = receiver.call{value:amount}(""); } else { IERC20 token = IERC20(asset); success = token.transfer(receiver, amount); } require (success, "Cannot Transfer"); } /// @notice transfer ERC20 asset to this contract function transferToHoldefi(address receiver, address asset, uint256 amount) internal { IERC20 token = IERC20(asset); bool success = token.transferFrom(msg.sender, receiver, amount); require (success, "Cannot Transfer"); } /// @notice Perform supply operation function supplyInternal(address account, address market, uint256 amount, uint16 referralCode) internal whenNotPaused("supply") marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); supplyData.balance = supplyData.balance.add(amount); supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.add(amount); emit Supply( msg.sender, account, market, amount, supplyData.balance, supplyData.interest, supplyData.currentIndex, referralCode ); } /// @notice Perform withdraw supply operation function withdrawSupplyInternal (address account, address market, uint256 amount) internal whenNotPaused("withdrawSupply") { MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); uint256 totalSuppliedBalance = supplyData.balance.add(supplyData.interest); require (totalSuppliedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalSuppliedBalance){ transferAmount = totalSuppliedBalance; } uint256 remaining = 0; if (transferAmount <= supplyData.interest) { supplyData.interest = supplyData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(supplyData.interest); supplyData.interest = 0; supplyData.balance = supplyData.balance.sub(remaining); } supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.sub(remaining); transferFromHoldefi(msg.sender, market, transferAmount); emit WithdrawSupply( msg.sender, account, market, transferAmount, supplyData.balance, supplyData.interest, supplyData.currentIndex ); } /// @notice Perform collateralize operation function collateralizeInternal (address account, address collateral, uint256 amount) internal whenNotPaused("collateralize") collateralIsActive(collateral) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } uint256 balance = collaterals[account][collateral].balance.add(amount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.add(amount); emit Collateralize(msg.sender, account, collateral, amount, balance); } /// @notice Perform withdraw collateral operation function withdrawCollateralInternal (address account, address collateral, uint256 amount) internal whenNotPaused("withdrawCollateral") { (uint256 balance,, uint256 borrowPowerValue, uint256 totalBorrowValue,) = getAccountCollateral(account, collateral); require (borrowPowerValue != 0, "Borrow power should not be zero"); uint256 collateralNedeed = 0; if (totalBorrowValue != 0) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; uint256 totalCollateralValue = totalBorrowValue.mul(valueToLoanRate).div(rateDecimals); collateralNedeed = holdefiPrices.getAssetAmountFromValue(collateral, totalCollateralValue); } uint256 maxWithdraw = balance.sub(collateralNedeed); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } balance = balance.sub(transferAmount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit WithdrawCollateral(msg.sender, account, collateral, transferAmount, balance); } /// @notice Perform borrow operation function borrowInternal (address account, address market, address collateral, uint256 amount, uint16 referralCode) internal whenNotPaused("borrow") marketIsActive(market) collateralIsActive(collateral) { require ( amount <= (marketAssets[market].totalSupply.sub(marketAssets[market].totalBorrow)), "Amount should be less than cash" ); (,, uint256 borrowPowerValue,,) = getAccountCollateral(account, collateral); uint256 assetToBorrowValue = holdefiPrices.getAssetValueFromAmount(market, amount); require ( borrowPowerValue >= assetToBorrowValue, "Borrow power should be more than new borrow value" ); MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); borrowData.balance = borrowData.balance.add(amount); borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.add(amount); transferFromHoldefi(msg.sender, market, amount); emit Borrow( msg.sender, account, market, collateral, amount, borrowData.balance, borrowData.interest, borrowData.currentIndex, referralCode ); } /// @notice Perform repay borrow operation function repayBorrowInternal (address account, address market, address collateral, uint256 amount) internal whenNotPaused("repayBorrow") { MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); require (totalBorrowedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalBorrowedBalance) { transferAmount = totalBorrowedBalance; if (market == ethAddress) { uint256 extra = amount.sub(transferAmount); transferFromHoldefi(msg.sender, ethAddress, extra); } } if (market != ethAddress) { transferToHoldefi(address(this), market, transferAmount); } uint256 remaining = 0; if (transferAmount <= borrowData.interest) { borrowData.interest = borrowData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(borrowData.interest); borrowData.interest = 0; borrowData.balance = borrowData.balance.sub(remaining); } borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(remaining); emit RepayBorrow ( msg.sender, account, market, collateral, transferAmount, borrowData.balance, borrowData.interest, borrowData.currentIndex ); } /// @notice Perform buy liquidated collateral operation function buyLiquidatedCollateralInternal (address market, address collateral, uint256 marketAmount) internal whenNotPaused("buyLiquidatedCollateral") { uint256 debt = marketDebt[collateral][market]; require (marketAmount <= debt, "Amount should be less than total liquidated assets" ); uint256 collateralAmountWithDiscount = getDiscountedCollateralAmount(market, collateral, marketAmount); uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; require ( collateralAmountWithDiscount <= totalLiquidatedCollateral, "Collateral amount with discount should be less than total liquidated assets" ); if (market != ethAddress) { transferToHoldefi(address(this), market, marketAmount); } collateralAssets[collateral].totalLiquidatedCollateral = totalLiquidatedCollateral.sub(collateralAmountWithDiscount); marketDebt[collateral][market] = debt.sub(marketAmount); holdefiCollaterals.withdraw(collateral, msg.sender, collateralAmountWithDiscount); emit BuyLiquidatedCollateral(market, collateral, marketAmount, collateralAmountWithDiscount); } /// @notice Perform deposit promotion reserve operation function depositPromotionReserveInternal (address market, uint256 amount) internal marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); marketAssets[market].promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(amountScaled); emit PromotionReserveDeposited(market, amount); } /// @notice Perform deposit liquidation reserve operation function depositLiquidationReserveInternal (address collateral, uint256 amount) internal collateralIsActive(ethAddress) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } collateralAssets[ethAddress].totalLiquidatedCollateral = collateralAssets[ethAddress].totalLiquidatedCollateral.add(msg.value); emit LiquidationReserveDeposited(ethAddress, msg.value); } }
Returns balance and interest of an account for a given market supplyInterest = accumulatedInterest + (balance (marketSupplyIndex - userLastSupplyInterestIndex)) account Supplier address to get supply information market Address of the given market return balance Supplied amount on the specified market return interest Profit earned return currentSupplyIndex Supply index for the given market at current time
function getAccountSupply(address account, address market) public view returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex) { balance = supplies[account][market].balance; (currentSupplyIndex,,) = getCurrentSupplyIndex(market); uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); interest = supplies[account][market].accumulatedInterest.add(deltaInterest); }
13,514,315
/** *Submitted for verification at Etherscan.io on 2021-08-26 */ // SPDX-License-Identifier: MIT // File: contracts\interfaces\ICauldron.sol pragma solidity 0.6.12; interface ICauldron { function userCollateralShare(address account) external view returns (uint); } // File: contracts\interfaces\IBentoBox.sol pragma solidity 0.6.12; interface IBentoBox { function toAmount(address _token, uint256 _share, bool _roundUp) external view returns (uint); } // File: contracts\interfaces\IRewardStaking.sol pragma solidity 0.6.12; interface IRewardStaking { function stakeFor(address, uint256) external; function stake( uint256) external; function withdraw(uint256 amount, bool claim) external; function withdrawAndUnwrap(uint256 amount, bool claim) external; function earned(address account) external view returns (uint256); function getReward() external; function getReward(address _account, bool _claimExtras) external; function extraRewardsLength() external view returns (uint256); function extraRewards(uint256 _pid) external view returns (address); function rewardToken() external view returns (address); function balanceOf(address _account) external view returns (uint256); } // File: contracts\interfaces\IConvexDeposits.sol pragma solidity 0.6.12; interface IConvexDeposits { function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool); function deposit(uint256 _amount, bool _lock, address _stakeAddress) external; } // File: contracts\interfaces\ICvx.sol pragma solidity 0.6.12; interface ICvx { function reductionPerCliff() external view returns(uint256); function totalSupply() external view returns(uint256); function totalCliffs() external view returns(uint256); function maxSupply() external view returns(uint256); } // File: contracts\interfaces\CvxMining.sol pragma solidity 0.6.12; library CvxMining{ ICvx public constant cvx = ICvx(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); function ConvertCrvToCvx(uint256 _amount) external view returns(uint256){ uint256 supply = cvx.totalSupply(); uint256 reductionPerCliff = cvx.reductionPerCliff(); uint256 totalCliffs = cvx.totalCliffs(); uint256 maxSupply = cvx.maxSupply(); uint256 cliff = supply / reductionPerCliff; //mint if below total cliffs if(cliff < totalCliffs){ //for reduction% take inverse of current cliff uint256 reduction = totalCliffs - cliff; //reduce _amount = _amount * reduction / totalCliffs; //supply cap check uint256 amtTillMax = maxSupply - supply; if(_amount > amtTillMax){ _amount = amtTillMax; } //mint return _amount; } return 0; } } // File: @openzeppelin\contracts\math\SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts\token\ERC20\IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin\contracts\utils\Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: node_modules\@openzeppelin\contracts\utils\Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts\token\ERC20\ERC20.sol pragma solidity >=0.6.0 <0.8.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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin\contracts\utils\ReentrancyGuard.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin\contracts\access\Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts\wrappers\ConvexStakingWrapper.sol pragma solidity 0.6.12; //Example of a tokenize a convex staked position. //if used as collateral some modifications will be needed to fit the specific platform //Based on Curve.fi's gauge wrapper implementations at https://github.com/curvefi/curve-dao-contracts/tree/master/contracts/gauges/wrappers contract ConvexStakingWrapper is ERC20, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct RewardType { address reward_token; address reward_pool; uint128 reward_integral; uint128 reward_remaining; mapping(address => uint256) reward_integral_for; mapping(address => uint256) claimable_reward; } uint256 public cvx_reward_integral; uint256 public cvx_reward_remaining; mapping(address => uint256) public cvx_reward_integral_for; mapping(address => uint256) public cvx_claimable_reward; //constants/immutables address public constant convexBooster = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address public constant cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); address public immutable curveToken; address public immutable convexToken; address public immutable convexPool; uint256 public immutable convexPoolId; address public immutable collateralVault; //rewards RewardType[] public rewards; //management bool public isShutdown = false; event Deposited(address indexed _user, address indexed _account, uint256 _amount, bool _wrapped); event Withdrawn(address indexed _user, uint256 _amount, bool _unwrapped); constructor(address _curveToken, address _convexToken, address _convexPool, uint256 _poolId, address _vault, string memory _nameTag, string memory _symbolTag) public ERC20( string( abi.encodePacked("Staked ", ERC20(_convexToken).name(), _nameTag ) ), string(abi.encodePacked("stk", ERC20(_convexToken).symbol(), _symbolTag)) ) Ownable() { curveToken = _curveToken; convexToken = _convexToken; convexPool = _convexPool; convexPoolId = _poolId; collateralVault = _vault; } function shutdown() external onlyOwner { isShutdown = true; } function setApprovals() external { IERC20(curveToken).safeApprove(convexBooster, 0); IERC20(curveToken).safeApprove(convexBooster, uint256(-1)); IERC20(convexToken).safeApprove(convexPool, 0); IERC20(convexToken).safeApprove(convexPool, uint256(-1)); } function addRewards() external { address mainPool = convexPool; if (rewards.length == 0) { rewards.push( RewardType({ reward_token: crv, reward_pool: mainPool, reward_integral: 0, reward_remaining: 0 }) ); } uint256 extraCount = IRewardStaking(mainPool).extraRewardsLength(); uint256 startIndex = rewards.length - 1; for (uint256 i = startIndex; i < extraCount; i++) { address extraPool = IRewardStaking(mainPool).extraRewards(i); rewards.push( RewardType({ reward_token: IRewardStaking(extraPool).rewardToken(), reward_pool: extraPool, reward_integral: 0, reward_remaining: 0 }) ); } } function rewardLength() external view returns(uint256) { return rewards.length; } function _getDepositedBalance(address _account) internal virtual view returns(uint256) { if (_account == address(0) || _account == collateralVault) { return 0; } //get balance from collateralVault return balanceOf(_account); } function _getTotalSupply() internal virtual view returns(uint256){ //override and add any supply needed (interest based growth) return totalSupply(); } function _calcCvxIntegral(address[2] memory _accounts, uint256[2] memory _balances, uint256 _supply, bool _isClaim) internal { uint256 bal = IERC20(cvx).balanceOf(address(this)); uint256 d_cvxreward = bal.sub(cvx_reward_remaining); if (_supply > 0) { cvx_reward_integral = cvx_reward_integral + d_cvxreward.mul(1e20).div(_supply); } //update user integrals for cvx for (uint256 u = 0; u < _accounts.length; u++) { //do not give rewards to address 0 if (_accounts[u] == address(0)) continue; if (_accounts[u] == collateralVault) continue; uint256 receiveable = cvx_claimable_reward[_accounts[u]].add(_balances[u].mul(cvx_reward_integral.sub(cvx_reward_integral_for[_accounts[u]])).div(1e20)); if(_isClaim){ if(receiveable > 0){ cvx_claimable_reward[_accounts[u]] = 0; IERC20(cvx).safeTransfer(_accounts[u], receiveable); bal = bal.sub(receiveable); } }else{ cvx_claimable_reward[_accounts[u]] = receiveable; } cvx_reward_integral_for[_accounts[u]] = cvx_reward_integral; } //update reward total cvx_reward_remaining = bal; } function _calcRewardIntegral(uint256 _index, address[2] memory _accounts, uint256[2] memory _balances, uint256 _supply, bool _isClaim) internal{ RewardType storage reward = rewards[_index]; //get difference in balance and remaining rewards //getReward is unguarded so we use reward_remaining to keep track of how much was actually claimed uint256 bal = IERC20(reward.reward_token).balanceOf(address(this)); uint256 d_reward = bal.sub(reward.reward_remaining); if (_supply > 0) { reward.reward_integral = reward.reward_integral + uint128(d_reward.mul(1e20).div(_supply)); } //update user integrals for (uint256 u = 0; u < _accounts.length; u++) { //do not give rewards to address 0 if (_accounts[u] == address(0)) continue; if (_accounts[u] == collateralVault) continue; if(_isClaim){ uint256 receiveable = reward.claimable_reward[_accounts[u]].add(_balances[u].mul( uint256(reward.reward_integral).sub(reward.reward_integral_for[_accounts[u]])).div(1e20)); if(receiveable > 0){ reward.claimable_reward[_accounts[u]] = 0; IERC20(reward.reward_token).safeTransfer(_accounts[u], receiveable); bal = bal.sub(receiveable); } }else{ reward.claimable_reward[_accounts[u]] = reward.claimable_reward[_accounts[u]].add(_balances[u].mul( uint256(reward.reward_integral).sub(reward.reward_integral_for[_accounts[u]])).div(1e20)); } reward.reward_integral_for[_accounts[u]] = reward.reward_integral; } //update remaining reward here since balance could have changed if claiming reward.reward_remaining = uint128(bal); } function _checkpoint(address[2] memory _accounts) internal { uint256 supply = _getTotalSupply(); uint256[2] memory depositedBalance; depositedBalance[0] = _getDepositedBalance(_accounts[0]); depositedBalance[1] = _getDepositedBalance(_accounts[1]); IRewardStaking(convexPool).getReward(address(this), true); uint256 rewardCount = rewards.length; for (uint256 i = 0; i < rewardCount; i++) { _calcRewardIntegral(i,_accounts,depositedBalance,supply,false); } _calcCvxIntegral(_accounts,depositedBalance,supply,false); } function _checkpointAndClaim(address[2] memory _accounts) internal { uint256 supply = _getTotalSupply(); uint256[2] memory depositedBalance; depositedBalance[0] = _getDepositedBalance(_accounts[0]); //only do first slot IRewardStaking(convexPool).getReward(address(this), true); uint256 rewardCount = rewards.length; for (uint256 i = 0; i < rewardCount; i++) { _calcRewardIntegral(i,_accounts,depositedBalance,supply,true); } _calcCvxIntegral(_accounts,depositedBalance,supply,true); } function user_checkpoint(address[2] calldata _accounts) external returns(bool) { _checkpoint([_accounts[0], _accounts[1]]); return true; } function totalBalanceOf(address _account) external view returns(uint256){ return _getDepositedBalance(_account); } function earned(address _account) external view returns(uint256[] memory claimable) { uint256 supply = _getTotalSupply(); // uint256 depositedBalance = _getDepositedBalance(_account); uint256 rewardCount = rewards.length; claimable = new uint256[](rewardCount + 1); for (uint256 i = 0; i < rewardCount; i++) { RewardType storage reward = rewards[i]; //change in reward is current balance - remaining reward + earned uint256 bal = IERC20(reward.reward_token).balanceOf(address(this)); uint256 d_reward = bal.sub(reward.reward_remaining); d_reward = d_reward.add(IRewardStaking(reward.reward_pool).earned(address(this))); uint256 I = reward.reward_integral; if (supply > 0) { I = I + d_reward.mul(1e20).div(supply); } uint256 newlyClaimable = _getDepositedBalance(_account).mul(I.sub(reward.reward_integral_for[_account])).div(1e20); claimable[i] = reward.claimable_reward[_account].add(newlyClaimable); //calc cvx here if(reward.reward_token == crv){ claimable[rewardCount] = cvx_claimable_reward[_account].add(CvxMining.ConvertCrvToCvx(newlyClaimable)); } } } function getReward(address _account) external { //claim directly in checkpoint logic to save a bit of gas _checkpointAndClaim([_account, address(0)]); } //deposit a curve token function deposit(uint256 _amount, address _to) external nonReentrant { require(!isShutdown, "shutdown"); //dont need to call checkpoint since _mint() will if (_amount > 0) { _mint(_to, _amount); IERC20(curveToken).safeTransferFrom(msg.sender, address(this), _amount); IConvexDeposits(convexBooster).deposit(convexPoolId, _amount, true); } emit Deposited(msg.sender, _to, _amount, true); } //stake a convex token function stake(uint256 _amount, address _to) external nonReentrant { require(!isShutdown, "shutdown"); //dont need to call checkpoint since _mint() will if (_amount > 0) { _mint(_to, _amount); IERC20(convexToken).safeTransferFrom(msg.sender, address(this), _amount); IRewardStaking(convexPool).stake(_amount); } emit Deposited(msg.sender, _to, _amount, false); } //withdraw to convex deposit token function withdraw(uint256 _amount) external nonReentrant { //dont need to call checkpoint since _burn() will if (_amount > 0) { _burn(msg.sender, _amount); IRewardStaking(convexPool).withdraw(_amount, false); IERC20(convexToken).safeTransfer(msg.sender, _amount); } emit Withdrawn(msg.sender, _amount, false); } //withdraw to underlying curve lp token function withdrawAndUnwrap(uint256 _amount) external nonReentrant { //dont need to call checkpoint since _burn() will if (_amount > 0) { _burn(msg.sender, _amount); IRewardStaking(convexPool).withdrawAndUnwrap(_amount, false); IERC20(curveToken).safeTransfer(msg.sender, _amount); } //events emit Withdrawn(msg.sender, _amount, true); } function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal override { _checkpoint([_from, _to]); } } // File: contracts\wrappers\ConvexStakingWrapperAbra.sol pragma solidity 0.6.12; //Staking wrapper for Abracadabra platform //use convex LP positions as collateral while still receiving rewards contract ConvexStakingWrapperAbra is ConvexStakingWrapper { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public cauldron; constructor(address _curveToken, address _convexToken, address _convexPool, uint256 _poolId) public ConvexStakingWrapper(_curveToken, _convexToken, _convexPool, _poolId, address(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966)," Abra", "-abra"){ } function setCauldron(address _cauldron) external onlyOwner{ require(cauldron == address(0),"!0"); cauldron = _cauldron; } function _getDepositedBalance(address _account) internal override view returns(uint256) { if (_account == address(0) || _account == collateralVault) { return 0; } //get collateral balance uint256 collateral = ICauldron(cauldron).userCollateralShare(_account); collateral = IBentoBox(collateralVault).toAmount(address(this), collateral, false); //add to balance of this token return balanceOf(_account).add(collateral); } }
uint256 depositedBalance = _getDepositedBalance(_account);change in reward is current balance - remaining reward + earnedcalc cvx here
function earned(address _account) external view returns(uint256[] memory claimable) { uint256 supply = _getTotalSupply(); uint256 rewardCount = rewards.length; claimable = new uint256[](rewardCount + 1); for (uint256 i = 0; i < rewardCount; i++) { RewardType storage reward = rewards[i]; uint256 bal = IERC20(reward.reward_token).balanceOf(address(this)); uint256 d_reward = bal.sub(reward.reward_remaining); d_reward = d_reward.add(IRewardStaking(reward.reward_pool).earned(address(this))); uint256 I = reward.reward_integral; if (supply > 0) { I = I + d_reward.mul(1e20).div(supply); } uint256 newlyClaimable = _getDepositedBalance(_account).mul(I.sub(reward.reward_integral_for[_account])).div(1e20); claimable[i] = reward.claimable_reward[_account].add(newlyClaimable); if(reward.reward_token == crv){ claimable[rewardCount] = cvx_claimable_reward[_account].add(CvxMining.ConvertCrvToCvx(newlyClaimable)); } } }
6,776,240
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/Types.sol"; import "../interfaces/ILedger.sol"; import "../interfaces/IOracleMaster.sol"; import "./utils/ReportUtils.sol"; contract Oracle { using ReportUtils for uint256; event Completed(uint256); // is already pushed flag bool public isPushed; // Current era report hashes uint256[] internal currentReportVariants; // Current era reports Types.OracleData[] private currentReports; // Then oracle member push report, its bit is set uint256 internal currentReportBitmask; // oracle master contract address address public ORACLE_MASTER; // linked ledger contract address address public LEDGER; // Allows function calls only from OracleMaster modifier onlyOracleMaster() { require(msg.sender == ORACLE_MASTER); _; } /** * @notice Initialize oracle contract * @param _oracleMaster oracle master address * @param _ledger linked ledger address */ function initialize(address _oracleMaster, address _ledger) external { require(ORACLE_MASTER == address(0), "ORACLE: ALREADY_INITIALIZED"); ORACLE_MASTER = _oracleMaster; LEDGER = _ledger; } /** * @notice Returns true if member is already reported * @param _index oracle member index * @return is reported indicator */ function isReported(uint256 _index) external view returns (bool) { return (currentReportBitmask & (1 << _index)) != 0; } /** * @notice Accept oracle report data, allowed to call only by oracle master contract * @param _index oracle member index * @param _quorum the minimum number of voted oracle members to accept a variant * @param _eraId current era id * @param _staking report data */ function reportRelay(uint256 _index, uint256 _quorum, uint64 _eraId, Types.OracleData calldata _staking) external onlyOracleMaster { { uint256 mask = 1 << _index; uint256 reportBitmask = currentReportBitmask; require(reportBitmask & mask == 0, "ORACLE: ALREADY_SUBMITTED"); currentReportBitmask = (reportBitmask | mask); } // return instantly if already got quorum and pushed data if (isPushed) { return; } // convert staking report into 31 byte hash. The last byte is used for vote counting uint256 variant = uint256(keccak256(abi.encode(_staking))) & ReportUtils.COUNT_OUTMASK; uint256 i = 0; uint256 _length = currentReportVariants.length; // iterate on all report variants we already have, limited by the oracle members maximum while (i < _length && currentReportVariants[i].isDifferent(variant)) ++i; if (i < _length) { if (currentReportVariants[i].getCount() + 1 >= _quorum) { _push(_eraId, _staking); } else { ++currentReportVariants[i]; // increment variant counter, see ReportUtils for details } } else { if (_quorum == 1) { _push(_eraId, _staking); } else { currentReportVariants.push(variant + 1); currentReports.push(_staking); } } } /** * @notice Change quorum threshold, allowed to call only by oracle master contract * @dev Method can trigger to pushing data to ledger if quorum threshold decreased and now for contract already reached new threshold. * @param _quorum new quorum threshold * @param _eraId current era id */ function softenQuorum(uint8 _quorum, uint64 _eraId) external onlyOracleMaster { (bool isQuorum, uint256 reportIndex) = _getQuorumReport(_quorum); if (isQuorum) { Types.OracleData memory report = _getStakeReport(reportIndex); _push( _eraId, report ); } } /** * @notice Clear data about current reporting, allowed to call only by oracle master contract */ function clearReporting() external onlyOracleMaster { _clearReporting(); } /** * @notice Returns report by given index * @param _index oracle member index * @return staking report data */ function _getStakeReport(uint256 _index) internal view returns (Types.OracleData storage staking) { assert(_index < currentReports.length); return currentReports[_index]; } /** * @notice Clear data about current reporting */ function _clearReporting() internal { currentReportBitmask = 0; isPushed = false; delete currentReportVariants; delete currentReports; } /** * @notice Push data to ledger */ function _push(uint64 _eraId, Types.OracleData memory report) internal { ILedger(LEDGER).pushData(_eraId, report); isPushed = true; } /** * @notice Return whether the `_quorum` is reached and the final report can be pushed */ function _getQuorumReport(uint256 _quorum) internal view returns (bool, uint256) { // check most frequent cases first: all reports are the same or no reports yet uint256 _length = currentReportVariants.length; if (_length == 1) { return (currentReportVariants[0].getCount() >= _quorum, 0); } else if (_length == 0) { return (false, type(uint256).max); } // if more than 2 kind of reports exist, choose the most frequent uint256 maxind = 0; uint256 repeat = 0; uint16 maxval = 0; uint16 cur = 0; for (uint256 i = 0; i < _length; ++i) { cur = currentReportVariants[i].getCount(); if (cur >= maxval) { if (cur == maxval) { ++repeat; } else { maxind = i; maxval = cur; repeat = 0; } } } return (maxval >= _quorum && repeat == 0, maxind); } }
_quorum new quorum threshold _eraId current era id/
function softenQuorum(uint8 _quorum, uint64 _eraId) external onlyOracleMaster { (bool isQuorum, uint256 reportIndex) = _getQuorumReport(_quorum); if (isQuorum) { Types.OracleData memory report = _getStakeReport(reportIndex); _push( _eraId, report ); } }
967,671
// SPDX-License-Identifier: MIT pragma solidity >=0.5.16; contract SupChain{ //List of events event orderCreated(uint256 _orderID, address _counterparty); event orderShipped(uint256 _orderID, address _counterparty); event orderStored(uint256 _orderID, address _counterparty); event orderOutOfCompliance(uint256 _orderID, address _counterparty); event orderCompleted(uint256 _orderID, address _counterparty); // Possible state of the order enum StateType {Created, InTransit, Stored, OutOfComplicance, Completed} //The status of an order on the supply chain struct Status{ // State of the order StateType state; // User taking over the order address currentCounterparty; // Previous user possessing the order address previousCounterparty; // IOT device monitoring the product temperature and location string iotDevice; // Actual location of the order string actualLocation; // Actual temperature of the environment int256 actualTemperature; // Next destination of the order string destination; // Date of creation/Shipping/Storage of the order uint256 date; } // An order of the supply chain struct Order{ // ID of the order uint256 orderID; //Number of time the order has been shipped/stored uint256 numberOfUpdate; // Barcode of the corder string barcode; // User starting the supply chain by introducing an order address initiatingCounterparty; // List the products inside the order string productsList; // Temperature minimal of the recommended environment int256 temperatureMinimal; // Temperature maximal of the recommended environment int256 temperatureMaximal; // Expiration date of the products uint256 expirationDate; // Last destination of the order string finalDestination; //Record the whole evolution of the status of an order mapping (uint256 => Status) statutes; } // Number of created order uint256 public orderCount = 0; //Just a test string test; //Map the entirety of the orders of the supply chain Order[] public orders; //Function allowing to know if an order is out of compliance or completed function verification(uint256 id, string memory currentLocation, int256 currentTemp, int256 typeOfOrderUpdate) internal returns(StateType){ StateType orderState; //We verify that the shipper/storer complied with the recommended order's storage/shipping environment if(currentTemp < orders[id].temperatureMinimal || currentTemp > orders[id].temperatureMaximal){ orderState = StateType.OutOfComplicance; emit orderOutOfCompliance(id, msg.sender); //We verify if the order has arrived to its final destination }else if(keccak256(abi.encodePacked(currentLocation))==keccak256(abi.encodePacked(orders[id].finalDestination))){ orderState = StateType.Completed; emit orderCompleted(id, msg.sender); }else if(typeOfOrderUpdate == 1){ orderState = StateType.Stored; emit orderStored(id, msg.sender); }else if(typeOfOrderUpdate == 2){ orderState = StateType.InTransit; emit orderShipped(id, msg.sender); } return orderState; } //Function allowing to create an order and add to the map with a null initial status function createOrder(string memory _barCode, string memory _productList, int256 _min, int256 _max, uint256 _expDate, string memory _fDestination) public{ //We create a new order, give it its id, and add the variable inputted by the user Order memory newOrder = Order(orderCount, 0, _barCode, msg.sender, _productList, _min, _max, _expDate, _fDestination); orders.push(newOrder); //We had the initial status of the order orders[orderCount].statutes[orders[orderCount].numberOfUpdate] = Status(StateType.Created, msg.sender, msg.sender, '', '', 0, '', now); emit orderCreated(orderCount, msg.sender); //We update the total number of order orderCount++; } //Function allowing to change the status of an order when being stored function storeOrder(uint256 id, string memory actualLoc, int256 actualTemp, string memory iotDevice) public{ //Get the correct state of the order StateType actualState = verification(id, actualLoc, actualTemp, 1); //We select the propert place where the status will be recorded orders[id].statutes[orders[id].numberOfUpdate + 1] = Status(actualState, msg.sender,orders[id].statutes[orders[id].numberOfUpdate].previousCounterparty, iotDevice, actualLoc, actualTemp, '', now); //We update the order number of update orders[id].numberOfUpdate++; } //Function allowing to change the status of an order when being shipped function shipOrder(uint256 id, string memory actualLoc, int256 actualTemp, string memory iotDevice, string memory nextDestination) public { StateType actualState = verification(id, actualLoc, actualTemp, 1); orders[id].statutes[orders[id].numberOfUpdate + 1] = Status(actualState, msg.sender, orders[id].statutes[orders[id].numberOfUpdate].previousCounterparty, iotDevice, actualLoc, actualTemp, nextDestination, now); orders[id].numberOfUpdate++; } //Function allowing to get the desired status of an order function getStatus(uint256 id, uint256 concernedStatusNumber) public view returns(StateType state, address cParty, address lParty, string memory device, string memory cLocation, int256 cTemp, string memory destination){ //Locate the concerned status of an order Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; //Return all the status's variable return(concernedStatus.state, concernedStatus.currentCounterparty, concernedStatus.previousCounterparty, concernedStatus.iotDevice, concernedStatus.actualLocation, concernedStatus.actualTemperature, concernedStatus.destination); } //Function allowing to get the desired order basic information function getOrder(uint256 id) public view returns(uint256 _id, uint256 updateNumber, string memory barCode, address iParty, string memory products, int256 min, int256 max, uint256 expDate, string memory fDestination){ Order memory o = orders[id]; return(o.orderID, o.numberOfUpdate, o.barcode, o.initiatingCounterparty, o.productsList, o.temperatureMinimal, o.temperatureMaximal, o.expirationDate, o.finalDestination); } //Getter function returning the number of orders created function getOrderLength() public view returns(uint256 length){ uint256 _length = orders.length; return _length; } //Getter function of the number of times an order was updated function getOrderNumberOfUpdate(uint256 id) public view returns(uint256 numberUpdate){ Order memory o = orders[id]; uint256 number = o.numberOfUpdate; return number; } //Getter function of the barcode of an order function getBarcode(uint256 id) public view returns(string memory barCode){ Order memory o = orders[id]; string memory barcode = o.barcode; return barcode; } //Getter function of the initiating counterparty of an order function getInitiatingCounterpary(uint256 id) public view returns(address iParty){ Order memory o = orders[id]; address party = o.initiatingCounterparty; return party; } //Getter function of the product list of an order function getProductList(uint256 id) public view returns(string memory products){ Order memory o = orders[id]; string memory product = o.productsList; return product; } //Getter function of an order's environment minimal temperature function getMinTemp(uint256 id) public view returns(int256 minTemp){ Order memory o = orders[id]; int256 temp = o.temperatureMinimal; return temp; } //Getter function of an order's environment maximal temperature function getMaxTemp(uint256 id) public view returns(int256 maxTemp){ Order memory o = orders[id]; int256 temp = o.temperatureMaximal; return temp; } //Getter function of the expiration date of an order function getExpiration(uint256 id) public view returns(uint256 expiration){ Order memory o = orders[id]; uint256 exp = o.expirationDate; return exp; } //Getter function of the last destination of an order function getLastDestination(uint256 id) public view returns(string memory lastDestination){ Order memory o = orders[id]; string memory dest = o.finalDestination; return dest; } //Getter function of the current state of an order function getState(uint256 id, uint256 concernedStatusNumber) public view returns(StateType state){ Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; return concernedStatus.state; } //Getter function of the current counterparty of an order function getCurrentCounterpary(uint256 id, uint256 concernedStatusNumber) public view returns(address cParty){ Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; return concernedStatus.currentCounterparty; } //Getter function of the previous counterparty of an order function getPreviousCounterpary(uint256 id, uint256 concernedStatusNumber) public view returns(address pParty){ Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; return concernedStatus.previousCounterparty; } //Getter function of the monitoring device of an order function getDevice(uint256 id, uint256 concernedStatusNumber) public view returns(string memory device){ Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; return concernedStatus.iotDevice; } //Getter function of the current location of an order function getCurrentLocation(uint256 id, uint256 concernedStatusNumber) public view returns(string memory cLocation){ Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; return concernedStatus.actualLocation; } //Getter function of the actual temperature of an order function getCurrentTemperature(uint256 id, uint256 concernedStatusNumber) public view returns(int256 cTemp){ Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; return concernedStatus.actualTemperature; } //Getter function of the next destination of an order function getNextDestination(uint256 id, uint256 concernedStatusNumber) public view returns(string memory nDestination){ Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; return concernedStatus.destination; } //Getter function of the date of creation/shipping/storage of an order function getDate(uint256 id, uint256 concernedStatusNumber) public view returns(uint256 date){ Status memory concernedStatus = orders[id].statutes[concernedStatusNumber]; return concernedStatus.date; } }
Function allowing to change the status of an order when being shipped
function shipOrder(uint256 id, string memory actualLoc, int256 actualTemp, string memory iotDevice, string memory nextDestination) public { StateType actualState = verification(id, actualLoc, actualTemp, 1); orders[id].statutes[orders[id].numberOfUpdate + 1] = Status(actualState, msg.sender, orders[id].statutes[orders[id].numberOfUpdate].previousCounterparty, iotDevice, actualLoc, actualTemp, nextDestination, now); orders[id].numberOfUpdate++; }
15,846,955
pragma solidity ^0.4.22; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title MultiOwnable * @dev The MultiOwnable contract has an owner address[], and provides basic authorization control */ contract MultiOwnable is Ownable { struct Types { mapping (address => bool) access; } mapping (uint => Types) private multiOwnersTypes; event AddOwner(uint _type, address addr); event AddOwner(uint[] types, address addr); event RemoveOwner(uint _type, address addr); modifier onlyMultiOwnersType(uint _type) { require(multiOwnersTypes[_type].access[msg.sender] || msg.sender == owner, "403"); _; } function onlyMultiOwnerType(uint _type, address _sender) public view returns(bool) { if (multiOwnersTypes[_type].access[_sender] || _sender == owner) { return true; } return false; } function addMultiOwnerType(uint _type, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); multiOwnersTypes[_type].access[_owner] = true; emit AddOwner(_type, _owner); return true; } function addMultiOwnerTypes(uint[] types, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); require(types.length > 0); for (uint i = 0; i < types.length; i++) { multiOwnersTypes[types[i]].access[_owner] = true; } emit AddOwner(types, _owner); return true; } function removeMultiOwnerType(uint types, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); multiOwnersTypes[types].access[_owner] = false; emit RemoveOwner(types, _owner); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract IBonus { function getCurrentDayBonus(uint startSaleDate, bool saleState) public view returns(uint); function _currentDay(uint startSaleDate, bool saleState) public view returns(uint); function getBonusData() public view returns(string); function getPreSaleBonusPercent() public view returns(uint); function getMinReachUsdPayInCents() public view returns(uint); } contract ICurrency { function getUsdAbsRaisedInCents() external view returns(uint); function getCoinRaisedBonusInWei() external view returns(uint); function getCoinRaisedInWei() public view returns(uint); function getUsdFromETH(uint ethWei) public view returns(uint); function getTokenFromETH(uint ethWei) public view returns(uint); function getCurrencyRate(string _ticker) public view returns(uint); function addPay(string _ticker, uint value, uint usdAmount, uint coinRaised, uint coinRaisedBonus) public returns(bool); function checkTickerExists(string ticker) public view returns(bool); function getUsdFromCurrency(string ticker, uint value) public view returns(uint); function getUsdFromCurrency(string ticker, uint value, uint usd) public view returns(uint); function getUsdFromCurrency(bytes32 ticker, uint value) public view returns(uint); function getUsdFromCurrency(bytes32 ticker, uint value, uint usd) public view returns(uint); function getTokenWeiFromUSD(uint usdCents) public view returns(uint); function editPay(bytes32 ticker, uint currencyValue, uint currencyUsdRaised, uint _usdAbsRaisedInCents, uint _coinRaisedInWei, uint _coinRaisedBonusInWei) public returns(bool); function getCurrencyList(string ticker) public view returns(bool active, uint usd, uint devision, uint raised, uint usdRaised, uint usdRaisedExchangeRate, uint counter, uint lastUpdate); function getCurrencyList(bytes32 ticker) public view returns(bool active, uint usd, uint devision, uint raised, uint usdRaised, uint usdRaisedExchangeRate, uint counter, uint lastUpdate); function getTotalUsdRaisedInCents() public view returns(uint); function getAllCurrencyTicker() public view returns(string); function getCoinUSDRate() public view returns(uint); function addPreSaleBonus(uint bonusToken) public returns(bool); function editPreSaleBonus(uint beforeBonus, uint afterBonus) public returns(bool); } contract IStorage { function processPreSaleBonus(uint minTotalUsdAmountInCents, uint bonusPercent, uint _start, uint _limit) external returns(uint); function checkNeedProcessPreSaleBonus(uint minTotalUsdAmountInCents) external view returns(bool); function getCountNeedProcessPreSaleBonus(uint minTotalUsdAmountInCents, uint start, uint limit) external view returns(uint); function reCountUserPreSaleBonus(uint uId, uint minTotalUsdAmountInCents, uint bonusPercent, uint maxPayTime) external returns(uint, uint); function getContributorIndexes(uint index) external view returns(uint); function checkNeedSendSHPC(bool proc) external view returns(bool); function getCountNeedSendSHPC(uint start, uint limit) external view returns(uint); function checkETHRefund(bool proc) external view returns(bool); function getCountETHRefund(uint start, uint limit) external view returns(uint); function addPayment(address _addr, string pType, uint _value, uint usdAmount, uint currencyUSD, uint tokenWithoutBonus, uint tokenBonus, uint bonusPercent, uint payId) public returns(bool); function addPayment(uint uId, string pType, uint _value, uint usdAmount, uint currencyUSD, uint tokenWithoutBonus, uint tokenBonus, uint bonusPercent, uint payId) public returns(bool); function checkUserIdExists(uint uId) public view returns(bool); function getContributorAddressById(uint uId) public view returns(address); function editPaymentByUserId(uint uId, uint payId, uint _payValue, uint _usdAmount, uint _currencyUSD, uint _totalToken, uint _tokenWithoutBonus, uint _tokenBonus, uint _bonusPercent) public returns(bool); function getUserPaymentById(uint uId, uint payId) public view returns(uint time, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus, uint tokenWithoutBonus, uint usdAbsRaisedInCents, bool refund); function checkWalletExists(address addr) public view returns(bool result); function checkReceivedCoins(address addr) public view returns(bool); function getContributorId(address addr) public view returns(uint); function getTotalCoin(address addr) public view returns(uint); function setReceivedCoin(uint uId) public returns(bool); function checkPreSaleReceivedBonus(address addr) public view returns(bool); function checkRefund(address addr) public view returns(bool); function setRefund(uint uId) public returns(bool); function getEthPaymentContributor(address addr) public view returns(uint); function refundPaymentByUserId(uint uId, uint payId) public returns(bool); function changeSupportChangeMainWallet(bool support) public returns(bool); } /** * @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 ShipCoin Crowdsale */ contract ShipCoinCrowdsale is MultiOwnable { using SafeMath for uint256; ERC20Basic public coinContract; IStorage public storageContract; ICurrency public currencyContract; IBonus public bonusContract; enum SaleState {NEW, PRESALE, CALCPSBONUS, SALE, END, REFUND} uint256 private constant ONE_DAY = 86400; SaleState public state; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } // minimum goal USD uint public softCapUSD = 500000000; // 5,000,000$ in cents // maximum goal USD uint public hardCapUSD = 6200000000; // 62,000,000$ in cents // maximum available SHPC with a bonus uint public maxDistributeCoin = 600000000 * 1 ether; //600,000,000 shpc (incl. bonus) // minimal accept payment uint public minimalContributionUSD = 100000; // 1000$ in cents // start and end timestamps where investments are allowed in PreSale uint public startPreSaleDate; uint public endPreSaleDate; uint public unfreezeRefundPreSale; uint public unfreezeRefundAll; // start and end timestamps where investments are allowed in sale uint public startSaleDate; uint public endSaleDate; bool public softCapAchieved = false; address public multiSig1; address public multiSig2; bool public multiSigReceivedSoftCap = false; /* Events */ event ChangeState(uint blockNumber, SaleState state); event ChangeMinContribUSD(uint oldAmount, uint newAmount); event ChangeStorageContract(address oldAddress, address newAddress); event ChangeCurrencyContract(address oldAddress, address newAddress); event ChangeCoinContract(address oldAddress, address newAddress); event ChangeBonusContract(address oldAddress, address newAddress); event AddPay(address contributor); event EditPay(address contributor); event SoftCapAchieved(uint amount); event ManualChangeStartPreSaleDate(uint oldDate, uint newDate); event ManualChangeEndPreSaleDate(uint oldDate, uint newDate); event ManualChangeStartSaleDate(uint oldDate, uint newDate); event ManualEndSaleDate(uint oldDate, uint newDate); event SendSHPCtoContributor(address contributor); event SoftCapChanged(); event Refund(address contributor); event RefundPay(address contributor); struct PaymentInfo { bytes32 pType; uint currencyUSD; uint bonusPercent; uint payValue; uint totalToken; uint tokenBonus; uint usdAbsRaisedInCents; bool refund; } struct CurrencyInfo { uint value; uint usdRaised; uint usdAbsRaisedInCents; uint coinRaisedInWei; uint coinRaisedBonusInWei; } struct EditPaymentInfo { uint usdAmount; uint currencyUSD; uint bonusPercent; uint totalToken; uint tokenWithoutBonus; uint tokenBonus; CurrencyInfo currency; } function () external whenNotPaused payable { buyTokens(msg.sender); } /** * @dev Run after deploy. Initialize initial variables * @param _coinAddress address coinContract * @param _storageContract address storageContract * @param _currencyContract address currencyContract * @param _bonusContract address bonusContract * @param _multiSig1 address multiSig where eth will be transferred * @param _startPreSaleDate timestamp * @param _endPreSaleDate timestamp * @param _startSaleDate timestamp * @param _endSaleDate timestamp */ function init( address _coinAddress, address _storageContract, address _currencyContract, address _bonusContract, address _multiSig1, uint _startPreSaleDate, uint _endPreSaleDate, uint _startSaleDate, uint _endSaleDate ) public onlyOwner { require(_coinAddress != address(0)); require(_storageContract != address(0)); require(_currencyContract != address(0)); require(_multiSig1 != address(0)); require(_bonusContract != address(0)); require(_startPreSaleDate > 0 && _startSaleDate > 0); require(_startSaleDate > _endPreSaleDate); require(_endSaleDate > _startSaleDate); require(startSaleDate == 0); coinContract = ERC20Basic(_coinAddress); storageContract = IStorage(_storageContract); currencyContract = ICurrency(_currencyContract); bonusContract = IBonus(_bonusContract); multiSig1 = _multiSig1; multiSig2 = 0x231121dFCB61C929BCdc0D1E6fC760c84e9A02ad; startPreSaleDate = _startPreSaleDate; endPreSaleDate = _endPreSaleDate; startSaleDate = _startSaleDate; endSaleDate = _endSaleDate; unfreezeRefundPreSale = _endSaleDate; unfreezeRefundAll = _endSaleDate.add(ONE_DAY); state = SaleState.NEW; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner { paused = true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner { paused = false; } /** * @dev Change the minimum amount in dollars indicated in cents to accept payment. * @param minContribUsd in cents */ function setMinimalContributionUSD(uint minContribUsd) public onlyOwner { require(minContribUsd > 100); // > 1$ uint oldMinAmount = minimalContributionUSD; minimalContributionUSD = minContribUsd; emit ChangeMinContribUSD(oldMinAmount, minimalContributionUSD); } /** * @dev Set the time when contributors can receive tokens * @param _time timestamp */ function setUnfreezeRefund(uint _time) public onlyOwner { require(_time > startSaleDate); unfreezeRefundPreSale = _time; unfreezeRefundAll = _time.add(ONE_DAY); } /** * @dev Change address ShipCoinStorage contracts. * @param _storageContract address ShipCoinStorage contracts */ function setStorageContract(address _storageContract) public onlyOwner { require(_storageContract != address(0)); address oldStorageContract = storageContract; storageContract = IStorage(_storageContract); emit ChangeStorageContract(oldStorageContract, storageContract); } /** * @dev Change address ShipCoin contracts. * @param _coinContract address ShipCoin contracts */ function setCoinContract(address _coinContract) public onlyOwner { require(_coinContract != address(0)); address oldCoinContract = coinContract; coinContract = ERC20Basic(_coinContract); emit ChangeCoinContract(oldCoinContract, coinContract); } /** * @dev Change address ShipCoinCurrency contracts. * @param _currencyContract address ShipCoinCurrency contracts */ function setCurrencyContract(address _currencyContract) public onlyOwner { require(_currencyContract != address(0)); address oldCurContract = currencyContract; currencyContract = ICurrency(_currencyContract); emit ChangeCurrencyContract(oldCurContract, currencyContract); } /** * @dev Change address ShipCoinBonusSystem contracts. * @param _bonusContract address ShipCoinBonusSystem contracts */ function setBonusContract(address _bonusContract) public onlyOwner { require(_bonusContract != address(0)); address oldContract = _bonusContract; bonusContract = IBonus(_bonusContract); emit ChangeBonusContract(oldContract, bonusContract); } /** * @dev Change address multiSig1. * @param _address address multiSig1 */ function setMultisig(address _address) public onlyOwner { require(_address != address(0)); multiSig1 = _address; } /** * @dev Set softCapUSD * @param _softCapUsdInCents uint softCapUSD > 100000 */ function setSoftCap(uint _softCapUsdInCents) public onlyOwner { require(_softCapUsdInCents > 100000); softCapUSD = _softCapUsdInCents; emit SoftCapChanged(); } /** * @dev Change maximum number of tokens sold * @param _maxCoin maxDistributeCoin */ function changeMaxDistributeCoin(uint _maxCoin) public onlyOwner { require(_maxCoin > 0 && _maxCoin >= currencyContract.getCoinRaisedInWei()); maxDistributeCoin = _maxCoin; } /** * @dev Change status. Start presale. */ function startPreSale() public onlyMultiOwnersType(1) { require(block.timestamp <= endPreSaleDate); require(state == SaleState.NEW); state = SaleState.PRESALE; emit ChangeState(block.number, state); } /** * @dev Change status. Start calculate presale bonus. */ function startCalculatePreSaleBonus() public onlyMultiOwnersType(5) { require(state == SaleState.PRESALE); state = SaleState.CALCPSBONUS; emit ChangeState(block.number, state); } /** * @dev Change status. Start sale. */ function startSale() public onlyMultiOwnersType(2) { require(block.timestamp <= endSaleDate); require(state == SaleState.CALCPSBONUS); //require(!storageContract.checkNeedProcessPreSaleBonus(getMinReachUsdPayInCents())); state = SaleState.SALE; emit ChangeState(block.number, state); } /** * @dev Change status. Set end if sale it was successful. */ function saleSetEnded() public onlyMultiOwnersType(3) { require((state == SaleState.SALE) || (state == SaleState.PRESALE)); require(block.timestamp >= startSaleDate); require(checkSoftCapAchieved()); state = SaleState.END; storageContract.changeSupportChangeMainWallet(false); emit ChangeState(block.number, state); } /** * @dev Change status. Set refund when sale did not reach softcap. */ function saleSetRefund() public onlyMultiOwnersType(4) { require((state == SaleState.SALE) || (state == SaleState.PRESALE)); require(block.timestamp >= endSaleDate); require(!checkSoftCapAchieved()); state = SaleState.REFUND; emit ChangeState(block.number, state); } /** * @dev Payable function. Processes contribution in ETH. */ function buyTokens(address _beneficiary) public whenNotPaused payable { require((state == SaleState.PRESALE && block.timestamp >= startPreSaleDate && block.timestamp <= endPreSaleDate) || (state == SaleState.SALE && block.timestamp >= startSaleDate && block.timestamp <= endSaleDate)); require(_beneficiary != address(0)); require(msg.value > 0); uint usdAmount = currencyContract.getUsdFromETH(msg.value); assert(usdAmount >= minimalContributionUSD); uint bonusPercent = 0; if (state == SaleState.SALE) { bonusPercent = bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); assert((totalToken > 0 && totalToken <= calculateMaxCoinIssued())); uint usdRate = currencyContract.getCurrencyRate("ETH"); assert(storageContract.addPayment(_beneficiary, "ETH", msg.value, usdAmount, usdRate, tokenWithoutBonus, tokenBonus, bonusPercent, 0)); assert(currencyContract.addPay("ETH", msg.value, usdAmount, totalToken, tokenBonus)); emit AddPay(_beneficiary); } /** * @dev Manually add alternative contribution payment. * @param ticker string * @param value uint * @param uId uint contributor identificator * @param _pId uint payment identificator * @param _currencyUSD uint current ticker rate (optional field) */ function addPay(string ticker, uint value, uint uId, uint _pId, uint _currencyUSD) public onlyMultiOwnersType(6) { require(value > 0); require(storageContract.checkUserIdExists(uId)); require(_pId > 0); string memory _ticker = ticker; uint _value = value; assert(currencyContract.checkTickerExists(_ticker)); uint usdAmount = currencyContract.getUsdFromCurrency(_ticker, _value, _currencyUSD); assert(usdAmount > 0); uint bonusPercent = 0; if (state == SaleState.SALE) { bonusPercent = bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); assert(tokenWithoutBonus > 0); uint usdRate = _currencyUSD > 0 ? _currencyUSD : currencyContract.getCurrencyRate(_ticker); uint pId = _pId; assert(storageContract.addPayment(uId, _ticker, _value, usdAmount, usdRate, tokenWithoutBonus, tokenBonus, bonusPercent, pId)); assert(currencyContract.addPay(_ticker, _value, usdAmount, totalToken, tokenBonus)); emit AddPay(storageContract.getContributorAddressById(uId)); } /** * @dev Edit contribution payment. * @param uId uint contributor identificator * @param payId uint payment identificator * @param value uint * @param _currencyUSD uint current ticker rate (optional field) * @param _bonusPercent uint current ticker rate (optional field) */ function editPay(uint uId, uint payId, uint value, uint _currencyUSD, uint _bonusPercent) public onlyMultiOwnersType(7) { require(value > 0); require(storageContract.checkUserIdExists(uId)); require(payId > 0); require((_bonusPercent == 0 || _bonusPercent <= getPreSaleBonusPercent())); PaymentInfo memory payment = getPaymentInfo(uId, payId); EditPaymentInfo memory paymentInfo = calcEditPaymentInfo(payment, value, _currencyUSD, _bonusPercent); assert(paymentInfo.tokenWithoutBonus > 0); assert(paymentInfo.currency.value > 0); assert(paymentInfo.currency.usdRaised > 0); assert(paymentInfo.currency.usdAbsRaisedInCents > 0); assert(paymentInfo.currency.coinRaisedInWei > 0); assert(currencyContract.editPay(payment.pType, paymentInfo.currency.value, paymentInfo.currency.usdRaised, paymentInfo.currency.usdAbsRaisedInCents, paymentInfo.currency.coinRaisedInWei, paymentInfo.currency.coinRaisedBonusInWei)); assert(storageContract.editPaymentByUserId(uId, payId, value, paymentInfo.usdAmount, paymentInfo.currencyUSD, paymentInfo.totalToken, paymentInfo.tokenWithoutBonus, paymentInfo.tokenBonus, paymentInfo.bonusPercent)); assert(reCountUserPreSaleBonus(uId)); emit EditPay(storageContract.getContributorAddressById(uId)); } /** * @dev Refund contribution payment. * @param uId uint * @param payId uint */ function refundPay(uint uId, uint payId) public onlyMultiOwnersType(18) { require(storageContract.checkUserIdExists(uId)); require(payId > 0); (CurrencyInfo memory currencyInfo, bytes32 pType) = calcCurrency(getPaymentInfo(uId, payId), 0, 0, 0, 0); assert(storageContract.refundPaymentByUserId(uId, payId)); assert(currencyContract.editPay(pType, currencyInfo.value, currencyInfo.usdRaised, currencyInfo.usdAbsRaisedInCents, currencyInfo.coinRaisedInWei, currencyInfo.coinRaisedBonusInWei)); assert(reCountUserPreSaleBonus(uId)); emit RefundPay(storageContract.getContributorAddressById(uId)); } /** * @dev Check if softCap is reached */ function checkSoftCapAchieved() public view returns(bool) { return softCapAchieved || getTotalUsdRaisedInCents() >= softCapUSD; } /** * @dev Set softCapAchieved=true if softCap is reached */ function activeSoftCapAchieved() public onlyMultiOwnersType(8) { require(checkSoftCapAchieved()); require(getCoinBalance() >= maxDistributeCoin); softCapAchieved = true; emit SoftCapAchieved(getTotalUsdRaisedInCents()); } /** * @dev Send ETH from contract balance to multiSig. */ function getEther() public onlyMultiOwnersType(9) { require(getETHBalance() > 0); require(softCapAchieved && (!multiSigReceivedSoftCap || (state == SaleState.END))); uint sendEther = (address(this).balance / 2); assert(sendEther > 0); address(multiSig1).transfer(sendEther); address(multiSig2).transfer(sendEther); multiSigReceivedSoftCap = true; } /** * @dev Return maximum amount buy token. */ function calculateMaxCoinIssued() public view returns (uint) { return maxDistributeCoin - currencyContract.getCoinRaisedInWei(); } /** * @dev Return raised SHPC in wei. */ function getCoinRaisedInWei() public view returns (uint) { return currencyContract.getCoinRaisedInWei(); } /** * @dev Return raised usd in cents. */ function getTotalUsdRaisedInCents() public view returns (uint) { return currencyContract.getTotalUsdRaisedInCents(); } /** * @dev Return all currency rate in json. */ function getAllCurrencyTicker() public view returns (string) { return currencyContract.getAllCurrencyTicker(); } /** * @dev Return SHPC price in cents. */ function getCoinUSDRate() public view returns (uint) { return currencyContract.getCoinUSDRate(); } /** * @dev Retrun SHPC balance in contract. */ function getCoinBalance() public view returns (uint) { return coinContract.balanceOf(address(this)); } /** * @dev Return balance ETH from contract. */ function getETHBalance() public view returns (uint) { return address(this).balance; } /** * @dev Processing of the data of the contributors. Bonus assignment for presale. * @param start uint > 0 * @param limit uint > 0 */ function processSetPreSaleBonus(uint start, uint limit) public onlyMultiOwnersType(10) { require(state == SaleState.CALCPSBONUS); require(start >= 0 && limit > 0); //require(storageContract.checkNeedProcessPreSaleBonus(getMinReachUsdPayInCents())); uint bonusToken = storageContract.processPreSaleBonus(getMinReachUsdPayInCents(), getPreSaleBonusPercent(), start, limit); if (bonusToken > 0) { assert(currencyContract.addPreSaleBonus(bonusToken)); } } /** * @dev Processing of the data of the contributor by uId. Bonus assignment for presale. * @param uId uint */ function reCountUserPreSaleBonus(uint uId) public onlyMultiOwnersType(11) returns(bool) { if (uint(state) > 1) { // > PRESALE uint maxPayTime = 0; if (state != SaleState.CALCPSBONUS) { maxPayTime = startSaleDate; } (uint befTokenBonus, uint aftTokenBonus) = storageContract.reCountUserPreSaleBonus(uId, getMinReachUsdPayInCents(), getPreSaleBonusPercent(), maxPayTime); assert(currencyContract.editPreSaleBonus(befTokenBonus, aftTokenBonus)); } return true; } /** * @dev Contributor get SHPC. */ function getCoins() public { return _getCoins(msg.sender); } /** * @dev Send contributors SHPC. * @param start uint * @param limit uint */ function sendSHPCtoContributors(uint start, uint limit) public onlyMultiOwnersType(12) { require(state == SaleState.END); require(start >= 0 && limit > 0); require(getCoinBalance() > 0); //require(storageContract.checkNeedSendSHPC(state == SaleState.END)); for (uint i = start; i < limit; i++) { uint uId = storageContract.getContributorIndexes(i); if (uId > 0) { address addr = storageContract.getContributorAddressById(uId); uint coins = storageContract.getTotalCoin(addr); if (!storageContract.checkReceivedCoins(addr) && storageContract.checkWalletExists(addr) && coins > 0 && ((storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundPreSale) || (!storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundAll))) { if (coinContract.transfer(addr, coins)) { storageContract.setReceivedCoin(uId); emit SendSHPCtoContributor(addr); } } } } } /** * @dev Set startPreSaleDate * @param date timestamp */ function setStartPreSaleDate(uint date) public onlyMultiOwnersType(13) { uint oldDate = startPreSaleDate; startPreSaleDate = date; emit ManualChangeStartPreSaleDate(oldDate, date); } /** * @dev Set startPreSaleDate * @param date timestamp */ function setEndPreSaleDate(uint date) public onlyMultiOwnersType(14) { uint oldDate = endPreSaleDate; endPreSaleDate = date; emit ManualChangeEndPreSaleDate(oldDate, date); } /** * @dev Set startSaleDate * @param date timestamp */ function setStartSaleDate(uint date) public onlyMultiOwnersType(15) { uint oldDate = startSaleDate; startSaleDate = date; emit ManualChangeStartSaleDate(oldDate, date); } /** * @dev Set endSaleDate * @param date timestamp */ function setEndSaleDate(uint date) public onlyMultiOwnersType(16) { uint oldDate = endSaleDate; endSaleDate = date; emit ManualEndSaleDate(oldDate, date); } /** * @dev Return SHPC from contract. When sale ended end contributor got SHPC. */ function getSHPCBack() public onlyMultiOwnersType(17) { require(state == SaleState.END); require(getCoinBalance() > 0); //require(!storageContract.checkNeedSendSHPC(state == SaleState.END)); coinContract.transfer(msg.sender, getCoinBalance()); } /** * @dev Refund ETH contributor. */ function refundETH() public { return _refundETH(msg.sender); } /** * @dev Refund ETH contributors. * @param start uint * @param limit uint */ function refundETHContributors(uint start, uint limit) public onlyMultiOwnersType(19) { require(state == SaleState.REFUND); require(start >= 0 && limit > 0); require(getETHBalance() > 0); //require(storageContract.checkETHRefund(state == SaleState.REFUND)); for (uint i = start; i < limit; i++) { uint uId = storageContract.getContributorIndexes(i); if (uId > 0) { address addr = storageContract.getContributorAddressById(uId); uint ethAmount = storageContract.getEthPaymentContributor(addr); if (!storageContract.checkRefund(addr) && storageContract.checkWalletExists(addr) && ethAmount > 0) { storageContract.setRefund(uId); addr.transfer(ethAmount); emit Refund(addr); } } } } /** * @dev Return pre-sale bonus getPreSaleBonusPercent. */ function getPreSaleBonusPercent() public view returns(uint) { return bonusContract.getPreSaleBonusPercent(); } /** * @dev Return pre-sale minReachUsdPayInCents. */ function getMinReachUsdPayInCents() public view returns(uint) { return bonusContract.getMinReachUsdPayInCents(); } /** * @dev Return current sale day. */ function _currentDay() public view returns(uint) { return bonusContract._currentDay(startSaleDate, (state == SaleState.SALE)); } /** * @dev Return current sale day bonus percent. */ function getCurrentDayBonus() public view returns(uint) { return bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } /** * @dev Return contributor payment info. * @param uId uint * @param pId uint */ function getPaymentInfo(uint uId, uint pId) private view returns(PaymentInfo) { (, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus,, uint usdAbsRaisedInCents, bool refund) = storageContract.getUserPaymentById(uId, pId); return PaymentInfo(pType, currencyUSD, bonusPercent, payValue, totalToken, tokenBonus, usdAbsRaisedInCents, refund); } /** * @dev Return recalculate payment data from old payment user. */ function calcEditPaymentInfo(PaymentInfo payment, uint value, uint _currencyUSD, uint _bonusPercent) private view returns(EditPaymentInfo) { (uint usdAmount, uint currencyUSD, uint bonusPercent) = getUsdAmountFromPayment(payment, value, _currencyUSD, _bonusPercent); (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); (CurrencyInfo memory currency,) = calcCurrency(payment, value, usdAmount, totalToken, tokenBonus); return EditPaymentInfo(usdAmount, currencyUSD, bonusPercent, totalToken, tokenWithoutBonus, tokenBonus, currency); } /** * @dev Return usd from payment amount. */ function getUsdAmountFromPayment(PaymentInfo payment, uint value, uint _currencyUSD, uint _bonusPercent) private view returns(uint, uint, uint) { _currencyUSD = _currencyUSD > 0 ? _currencyUSD : payment.currencyUSD; _bonusPercent = _bonusPercent > 0 ? _bonusPercent : payment.bonusPercent; uint usdAmount = currencyContract.getUsdFromCurrency(payment.pType, value, _currencyUSD); return (usdAmount, _currencyUSD, _bonusPercent); } /** * @dev Return payment SHPC data from usd amount and bonusPercent */ function calcToken(uint usdAmount, uint _bonusPercent) private view returns(uint, uint, uint) { uint tokenWithoutBonus = currencyContract.getTokenWeiFromUSD(usdAmount); uint tokenBonus = _bonusPercent > 0 ? tokenWithoutBonus.mul(_bonusPercent).div(100) : 0; uint totalToken = tokenBonus > 0 ? tokenWithoutBonus.add(tokenBonus) : tokenWithoutBonus; return (totalToken, tokenWithoutBonus, tokenBonus); } /** * @dev Calculate currency data when edit user payment data */ function calcCurrency(PaymentInfo payment, uint value, uint usdAmount, uint totalToken, uint tokenBonus) private view returns(CurrencyInfo, bytes32) { (,,, uint currencyValue, uint currencyUsdRaised,,,) = currencyContract.getCurrencyList(payment.pType); uint usdAbsRaisedInCents = currencyContract.getUsdAbsRaisedInCents(); uint coinRaisedInWei = currencyContract.getCoinRaisedInWei(); uint coinRaisedBonusInWei = currencyContract.getCoinRaisedBonusInWei(); currencyValue -= payment.payValue; currencyUsdRaised -= payment.usdAbsRaisedInCents; usdAbsRaisedInCents -= payment.usdAbsRaisedInCents; coinRaisedInWei -= payment.totalToken; coinRaisedBonusInWei -= payment.tokenBonus; currencyValue += value; currencyUsdRaised += usdAmount; usdAbsRaisedInCents += usdAmount; coinRaisedInWei += totalToken; coinRaisedBonusInWei += tokenBonus; return (CurrencyInfo(currencyValue, currencyUsdRaised, usdAbsRaisedInCents, coinRaisedInWei, coinRaisedBonusInWei), payment.pType); } /** * @dev Getting the SHPC from the contributor */ function _getCoins(address addr) private { require(state == SaleState.END); require(storageContract.checkWalletExists(addr)); require(!storageContract.checkReceivedCoins(addr)); require((storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundPreSale) || (!storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundAll)); uint uId = storageContract.getContributorId(addr); uint coins = storageContract.getTotalCoin(addr); assert(uId > 0 && coins > 0); if (coinContract.transfer(addr, coins)) { storageContract.setReceivedCoin(uId); emit SendSHPCtoContributor(addr); } } /** * @dev Refund ETH contributor when sale not reach softcap. */ function _refundETH(address addr) private { require(state == SaleState.REFUND); require(storageContract.checkWalletExists(addr)); require(!storageContract.checkRefund(addr)); uint uId = storageContract.getContributorId(addr); uint ethAmount = storageContract.getEthPaymentContributor(addr); assert(uId > 0 && ethAmount > 0 && getETHBalance() >= ethAmount); storageContract.setRefund(uId); addr.transfer(ethAmount); emit Refund(addr); } }
Processing of the data of the contributor by uId. Bonus assignment for presale. uId uint/
function reCountUserPreSaleBonus(uint uId) public onlyMultiOwnersType(11) returns(bool) { uint maxPayTime = 0; if (state != SaleState.CALCPSBONUS) { maxPayTime = startSaleDate; } (uint befTokenBonus, uint aftTokenBonus) = storageContract.reCountUserPreSaleBonus(uId, getMinReachUsdPayInCents(), getPreSaleBonusPercent(), maxPayTime); assert(currencyContract.editPreSaleBonus(befTokenBonus, aftTokenBonus)); } return true;
15,856,476
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.13; // OpenZeppelin Contracts (last updated v4.6.0-rc.0) (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount ) external returns (bool); } /// @notice An error used to indicate that an argument passed to a function is illegal or /// inappropriate. /// /// @param message The error message. error IllegalArgument(string message); /// @notice An error used to indicate that a function has encountered an unrecoverable state. /// /// @param message The error message. error IllegalState(string message); /// @notice An error used to indicate that an operation is unsupported. /// /// @param message The error message. error UnsupportedOperation(string message); /// @notice An error used to indicate that a message sender tried to execute a privileged function. /// /// @param message The error message. error Unauthorized(string message); /// @title Multicall /// @author Uniswap Labs /// /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall { error MulticallFailed(bytes data, bytes result); function multicall( bytes[] calldata data ) external payable returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { revert MulticallFailed(data[i], result); } results[i] = result; } } } /// @title Mutex /// @author Alchemix Finance /// /// @notice Provides a mutual exclusion lock for implementing contracts. abstract contract Mutex { enum State { RESERVED, UNLOCKED, LOCKED } /// @notice The lock state. State private _lockState = State.UNLOCKED; /// @dev A modifier which acquires the mutex. modifier lock() { _claimLock(); _; _freeLock(); } /// @dev Gets if the mutex is locked. /// /// @return if the mutex is locked. function _isLocked() internal view returns (bool) { return _lockState == State.LOCKED; } /// @dev Claims the lock. If the lock is already claimed, then this will revert. function _claimLock() internal { // Check that the lock has not been claimed yet. if (_lockState != State.UNLOCKED) { revert IllegalState("Lock already claimed"); } // Claim the lock. _lockState = State.LOCKED; } /// @dev Frees the lock. function _freeLock() internal { _lockState = State.UNLOCKED; } } /// @title IERC20TokenReceiver /// @author Alchemix Finance interface IERC20TokenReceiver { /// @notice Informs implementors of this interface that an ERC20 token has been transferred. /// /// @param token The token that was transferred. /// @param value The amount of the token that was transferred. function onERC20Received(address token, uint256 value) external; } interface IConvexBooster { function deposit(uint256 pid, uint256 amount, bool stake) external returns (bool); function withdraw(uint256 pid, uint256 amount) external returns (bool); } interface IConvexRewards { function rewardToken() external view returns (IERC20); function earned(address account) external view returns (uint256); function extraRewards(uint256 index) external view returns (address); function balanceOf(address account) external returns(uint256); function withdraw(uint256 amount, bool claim) external returns (bool); function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool); function getReward() external returns (bool); function getReward(address recipient, bool claim) external returns (bool); function stake(uint256 amount) external returns (bool); function stakeFor(address account, uint256 amount) external returns (bool); } interface IConvexToken is IERC20 { function maxSupply() external view returns (uint256); function totalCliffs() external view returns (uint256); function reductionPerCliff() external view returns (uint256); } /// @dev TODO uint256 constant NUM_META_COINS = 2; interface IStableMetaPool is IERC20 { function get_balances() external view returns (uint256[NUM_META_COINS] memory); function coins(uint256 index) external view returns (IERC20); function A() external view returns (uint256); function get_virtual_price() external view returns (uint256); function calc_token_amount( uint256[NUM_META_COINS] calldata amounts, bool deposit ) external view returns (uint256 amount); function add_liquidity( uint256[NUM_META_COINS] calldata amounts, uint256 minimumMintAmount ) external returns (uint256 minted); function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256 dy); function get_dy_underlying(int128 i, int128 j, uint256 dx, uint256[NUM_META_COINS] calldata balances) external view returns (uint256 dy); function exchange(int128 i, int128 j, uint256 dx, uint256 minimumDy) external returns (uint256); function remove_liquidity(uint256 amount, uint256[NUM_META_COINS] calldata minimumAmounts) external; function remove_liquidity_imbalance( uint256[NUM_META_COINS] calldata amounts, uint256 maximumBurnAmount ) external returns (uint256); function calc_withdraw_one_coin(uint256 tokenAmount, int128 i) external view returns (uint256); function remove_liquidity_one_coin( uint256 tokenAmount, int128 i, uint256 minimumAmount ) external returns (uint256); function get_price_cumulative_last() external view returns (uint256[NUM_META_COINS] calldata); function block_timestamp_last() external view returns (uint256); function get_twap_balances( uint256[NUM_META_COINS] calldata firstBalances, uint256[NUM_META_COINS] calldata lastBalances, uint256 timeElapsed ) external view returns (uint256[NUM_META_COINS] calldata); function get_dy( int128 i, int128 j, uint256 dx, uint256[NUM_META_COINS] calldata balances ) external view returns (uint256); } uint256 constant NUM_STABLE_COINS = 3; interface IStableSwap3Pool { function coins(uint256 index) external view returns (IERC20); function A() external view returns (uint256); function get_virtual_price() external view returns (uint256); function calc_token_amount( uint256[NUM_STABLE_COINS] calldata amounts, bool deposit ) external view returns (uint256 amount); function add_liquidity(uint256[NUM_STABLE_COINS] calldata amounts, uint256 minimumMintAmount) external; function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256 dy); function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns (uint256 dy); function exchange(int128 i, int128 j, uint256 dx, uint256 minimumDy) external returns (uint256); function remove_liquidity(uint256 amount, uint256[NUM_STABLE_COINS] calldata minimumAmounts) external; function remove_liquidity_imbalance( uint256[NUM_STABLE_COINS] calldata amounts, uint256 maximumBurnAmount ) external; function calc_withdraw_one_coin(uint256 tokenAmount, int128 i) external view returns (uint256); function remove_liquidity_one_coin( uint256 tokenAmount, int128 i, uint256 minimumAmount ) external; } /// @title IERC20Metadata /// @author Alchemix Finance interface IERC20Metadata { /// @notice Gets the name of the token. /// /// @return The name. function name() external view returns (string memory); /// @notice Gets the symbol of the token. /// /// @return The symbol. function symbol() external view returns (string memory); /// @notice Gets the number of decimals that the token has. /// /// @return The number of decimals. function decimals() external view returns (uint8); } /// @title SafeERC20 /// @author Alchemix Finance library SafeERC20 { /// @notice An error used to indicate that a call to an ERC20 contract failed. /// /// @param target The target address. /// @param success If the call to the token was a success. /// @param data The resulting data from the call. This is error data when the call was not a /// success. Otherwise, this is malformed data when the call was a success. error ERC20CallFailed(address target, bool success, bytes data); /// @dev A safe function to get the decimals of an ERC20 token. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an /// unexpected value. /// /// @param token The target token. /// /// @return The amount of decimals of the token. function expectDecimals(address token) internal view returns (uint8) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint8)); } /// @dev Transfers tokens to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an /// unexpected value. /// /// @param token The token to transfer. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransfer(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20.transfer.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Approves tokens for the smart contract. /// /// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an /// unexpected value. /// /// @param token The token to approve. /// @param spender The contract to spend the tokens. /// @param value The amount of tokens to approve. function safeApprove(address token, address spender, uint256 value) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20.approve.selector, spender, value) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Transfer tokens from one address to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an /// unexpected value. /// /// @param token The token to transfer. /// @param owner The address of the owner. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20.transferFrom.selector, owner, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } } /// @notice A struct used to define initialization parameters. This is not included /// in the contract to prevent naming collisions. struct InitializationParams { address admin; address operator; address rewardReceiver; address transmuterBuffer; IERC20 curveToken; IStableSwap3Pool threePool; IStableMetaPool metaPool; uint256 threePoolSlippage; uint256 metaPoolSlippage; IConvexToken convexToken; IConvexBooster convexBooster; IConvexRewards convexRewards; uint256 convexPoolId; } /// @dev The amount of precision that slippage parameters have. uint256 constant SLIPPAGE_PRECISION = 1e4; /// @dev The amount of precision that curve pools use for price calculations. uint256 constant CURVE_PRECISION = 1e18; /// @notice Enumerations for 3pool assets. /// /// @dev Do not change the order of these fields. enum ThreePoolAsset { DAI, USDC, USDT } /// @notice Enumerations for meta pool assets. /// /// @dev Do not change the order of these fields. enum MetaPoolAsset { ALUSD, THREE_POOL } /// @title ThreePoolAssetManager /// @author Alchemix Finance contract ThreePoolAssetManager is Multicall, Mutex, IERC20TokenReceiver { /// @notice Emitted when the admin is updated. /// /// @param admin The admin. event AdminUpdated(address admin); /// @notice Emitted when the pending admin is updated. /// /// @param pendingAdmin The pending admin. event PendingAdminUpdated(address pendingAdmin); /// @notice Emitted when the operator is updated. /// /// @param operator The operator. event OperatorUpdated(address operator); /// @notice Emitted when the reward receiver is updated. /// /// @param rewardReceiver The reward receiver. event RewardReceiverUpdated(address rewardReceiver); /// @notice Emitted when the transmuter buffer is updated. /// /// @param transmuterBuffer The transmuter buffer. event TransmuterBufferUpdated(address transmuterBuffer); /// @notice Emitted when the 3pool slippage is updated. /// /// @param threePoolSlippage The 3pool slippage. event ThreePoolSlippageUpdated(uint256 threePoolSlippage); /// @notice Emitted when the meta pool slippage is updated. /// /// @param metaPoolSlippage The meta pool slippage. event MetaPoolSlippageUpdated(uint256 metaPoolSlippage); /// @notice Emitted when 3pool tokens are minted. /// /// @param amounts The amounts of each 3pool asset used to mint liquidity. /// @param mintedThreePoolTokens The amount of 3pool tokens minted. event MintThreePoolTokens(uint256[NUM_STABLE_COINS] amounts, uint256 mintedThreePoolTokens); /// @notice Emitted when 3pool tokens are minted. /// /// @param asset The 3pool asset used to mint 3pool tokens. /// @param amount The amount of the asset used to mint 3pool tokens. /// @param mintedThreePoolTokens The amount of 3pool tokens minted. event MintThreePoolTokens(ThreePoolAsset asset, uint256 amount, uint256 mintedThreePoolTokens); /// @notice Emitted when 3pool tokens are burned. /// /// @param asset The 3pool asset that was received. /// @param amount The amount of 3pool tokens that were burned. /// @param withdrawn The amount of the 3pool asset that was withdrawn. event BurnThreePoolTokens(ThreePoolAsset asset, uint256 amount, uint256 withdrawn); /// @notice Emitted when meta pool tokens are minted. /// /// @param amounts The amounts of each meta pool asset used to mint liquidity. /// @param mintedThreePoolTokens The amount of meta pool tokens minted. event MintMetaPoolTokens(uint256[NUM_META_COINS] amounts, uint256 mintedThreePoolTokens); /// @notice Emitted when meta tokens are minted. /// /// @param asset The asset used to mint meta pool tokens. /// @param amount The amount of the asset used to mint meta pool tokens. /// @param minted The amount of meta pool tokens minted. event MintMetaPoolTokens(MetaPoolAsset asset, uint256 amount, uint256 minted); /// @notice Emitted when meta pool tokens are burned. /// /// @param asset The meta pool asset that was received. /// @param amount The amount of meta pool tokens that were burned. /// @param withdrawn The amount of the asset that was withdrawn. event BurnMetaPoolTokens(MetaPoolAsset asset, uint256 amount, uint256 withdrawn); /// @notice Emitted when meta pool tokens are deposited into convex. /// /// @param amount The amount of meta pool tokens that were deposited. /// @param success If the operation was successful. event DepositMetaPoolTokens(uint256 amount, bool success); /// @notice Emitted when meta pool tokens are withdrawn from convex. /// /// @param amount The amount of meta pool tokens that were withdrawn. /// @param success If the operation was successful. event WithdrawMetaPoolTokens(uint256 amount, bool success); /// @notice Emitted when convex rewards are claimed. /// /// @param success If the operation was successful. /// @param amountCurve The amount of curve tokens sent to the reward recipient. /// @param amountConvex The amount of convex tokens sent to the reward recipient. event ClaimRewards(bool success, uint256 amountCurve, uint256 amountConvex); /// @notice Emitted when 3pool assets are sent to the transmuter buffer. /// /// @param asset The 3pool asset that was reclaimed. /// @param amount The amount of the asset that was reclaimed. event ReclaimThreePoolAsset(ThreePoolAsset asset, uint256 amount); /// @notice The admin. address public admin; /// @notice The current pending admin. address public pendingAdmin; /// @notice The operator. address public operator; // @notice The reward receiver. address public rewardReceiver; /// @notice The transmuter buffer. address public transmuterBuffer; /// @notice The curve token. IERC20 public immutable curveToken; /// @notice The 3pool contract. IStableSwap3Pool public immutable threePool; /// @notice The meta pool contract. IStableMetaPool public immutable metaPool; /// @notice The amount of slippage that will be tolerated when depositing and withdrawing assets /// from the stable swap pool. In units of basis points. uint256 public threePoolSlippage; /// @notice The amount of slippage that will be tolerated when depositing and withdrawing assets /// from the meta pool. In units of basis points. uint256 public metaPoolSlippage; /// @notice The convex token. IConvexToken public immutable convexToken; /// @notice The convex booster contract. IConvexBooster public immutable convexBooster; /// @notice The convex rewards contract. IConvexRewards public immutable convexRewards; /// @notice The convex pool identifier. uint256 public immutable convexPoolId; /// @dev A cache of the tokens that the stable swap pool supports. IERC20[NUM_STABLE_COINS] private _threePoolAssetCache; /// @dev A cache of the tokens that the meta pool supports. IERC20[NUM_META_COINS] private _metaPoolAssetCache; /// @dev A modifier which reverts if the message sender is not the admin. modifier onlyAdmin() { if (msg.sender != admin) { revert Unauthorized("Not admin"); } _; } /// @dev A modifier which reverts if the message sender is not the operator. modifier onlyOperator() { if (msg.sender != operator) { revert Unauthorized("Not operator"); } _; } constructor(InitializationParams memory params) { admin = params.admin; operator = params.operator; rewardReceiver = params.rewardReceiver; transmuterBuffer = params.transmuterBuffer; curveToken = params.curveToken; threePool = params.threePool; metaPool = params.metaPool; threePoolSlippage = params.threePoolSlippage; metaPoolSlippage = params.metaPoolSlippage; convexToken = params.convexToken; convexBooster = params.convexBooster; convexRewards = params.convexRewards; convexPoolId = params.convexPoolId; for (uint256 i = 0; i < NUM_STABLE_COINS; i++) { _threePoolAssetCache[i] = params.threePool.coins(i); } for (uint256 i = 0; i < NUM_META_COINS; i++) { _metaPoolAssetCache[i] = params.metaPool.coins(i); } emit AdminUpdated(admin); emit OperatorUpdated(operator); emit RewardReceiverUpdated(rewardReceiver); emit TransmuterBufferUpdated(transmuterBuffer); emit ThreePoolSlippageUpdated(threePoolSlippage); emit MetaPoolSlippageUpdated(metaPoolSlippage); } /// @notice Gets the amount of meta pool tokens that this contract has in reserves. /// /// @return The reserves. function metaPoolReserves() external view returns (uint256) { return metaPool.balanceOf(address(this)); } /// @notice Gets the amount of a 3pool asset that this contract has in reserves. /// /// @param asset The 3pool asset. /// /// @return The reserves. function threePoolAssetReserves(ThreePoolAsset asset) external view returns (uint256) { IERC20 token = getTokenForThreePoolAsset(asset); return token.balanceOf(address(this)); } /// @notice Gets the amount of a meta pool asset that this contract has in reserves. /// /// @param asset The meta pool asset. /// /// @return The reserves. function metaPoolAssetReserves(MetaPoolAsset asset) external view returns (uint256) { IERC20 token = getTokenForMetaPoolAsset(asset); return token.balanceOf(address(this)); } /// @notice Gets the amount of a 3pool asset that one alUSD is worth. /// /// @param asset The 3pool asset. /// /// @return The amount of the underying. function exchangeRate(ThreePoolAsset asset) public view returns (uint256) { IERC20 alUSD = getTokenForMetaPoolAsset(MetaPoolAsset.ALUSD); uint256[NUM_META_COINS] memory metaBalances = metaPool.get_balances(); uint256 amountThreePool = metaPool.get_dy( int128(uint128(uint256(MetaPoolAsset.ALUSD))), int128(uint128(uint256(MetaPoolAsset.THREE_POOL))), 10**SafeERC20.expectDecimals(address(alUSD)), metaBalances ); return threePool.calc_withdraw_one_coin(amountThreePool, int128(uint128(uint256(asset)))); } /// @dev Struct used to declare local variables for the calculate rebalance function. struct CalculateRebalanceLocalVars { uint256 minimum; uint256 maximum; uint256 minimumDistance; uint256 minimizedBalance; uint256 startingBalance; } /// @notice Calculates how much alUSD or 3pool needs to be added or removed from the metapool /// to reach a target exchange rate for a specified 3pool asset. /// /// @param rebalanceAsset The meta pool asset to use to rebalance the pool. /// @param targetExchangeAsset The 3pool asset to balance the price relative to. /// @param targetExchangeRate The target exchange rate. /// /// @return delta The amount of alUSD or 3pool that needs to be added or removed from the pool. /// @return add If the alUSD or 3pool needs to be removed or added. function calculateRebalance( MetaPoolAsset rebalanceAsset, ThreePoolAsset targetExchangeAsset, uint256 targetExchangeRate ) public view returns (uint256 delta, bool add) { uint256 decimals; { IERC20 alUSD = getTokenForMetaPoolAsset(MetaPoolAsset.ALUSD); decimals = SafeERC20.expectDecimals(address(alUSD)); } uint256[NUM_META_COINS] memory startingBalances = metaPool.get_balances(); uint256[NUM_META_COINS] memory currentBalances = [startingBalances[0], startingBalances[1]]; CalculateRebalanceLocalVars memory v; v.minimum = 0; v.maximum = type(uint96).max; v.minimumDistance = type(uint256).max; v.minimizedBalance = type(uint256).max; v.startingBalance = startingBalances[uint256(rebalanceAsset)]; uint256 previousBalance; for (uint256 i = 0; i < 256; i++) { uint256 examineBalance; if ((examineBalance = (v.maximum + v.minimum) / 2) == previousBalance) break; currentBalances[uint256(rebalanceAsset)] = examineBalance; uint256 amountThreePool = metaPool.get_dy( int128(uint128(uint256(MetaPoolAsset.ALUSD))), int128(uint128(uint256(MetaPoolAsset.THREE_POOL))), 10**decimals, currentBalances ); uint256 exchangeRate = threePool.calc_withdraw_one_coin( amountThreePool, int128(uint128(uint256(targetExchangeAsset))) ); uint256 distance = abs(exchangeRate, targetExchangeRate); if (distance < v.minimumDistance) { v.minimumDistance = distance; v.minimizedBalance = examineBalance; } else if(distance == v.minimumDistance) { uint256 examineDelta = abs(examineBalance, v.startingBalance); uint256 currentDelta = abs(v.minimizedBalance, v.startingBalance); v.minimizedBalance = currentDelta > examineDelta ? examineBalance : v.minimizedBalance; } if (exchangeRate > targetExchangeRate) { if (rebalanceAsset == MetaPoolAsset.ALUSD) { v.minimum = examineBalance; } else { v.maximum = examineBalance; } } else { if (rebalanceAsset == MetaPoolAsset.ALUSD) { v.maximum = examineBalance; } else { v.minimum = examineBalance; } } previousBalance = examineBalance; } return v.minimizedBalance > v.startingBalance ? (v.minimizedBalance - v.startingBalance, true) : (v.startingBalance - v.minimizedBalance, false); } /// @notice Gets the amount of curve tokens and convex tokens that can be claimed. /// /// @return amountCurve The amount of curve tokens available. /// @return amountConvex The amount of convex tokens available. function claimableRewards() public view returns (uint256 amountCurve, uint256 amountConvex) { amountCurve = convexRewards.earned(address(this)); amountConvex = _getEarnedConvex(amountCurve); } /// @notice Gets the ERC20 token associated with a 3pool asset. /// /// @param asset The asset to get the token for. /// /// @return The token. function getTokenForThreePoolAsset(ThreePoolAsset asset) public view returns (IERC20) { uint256 index = uint256(asset); if (index >= NUM_STABLE_COINS) { revert IllegalArgument("Asset index out of bounds"); } return _threePoolAssetCache[index]; } /// @notice Gets the ERC20 token associated with a meta pool asset. /// /// @param asset The asset to get the token for. /// /// @return The token. function getTokenForMetaPoolAsset(MetaPoolAsset asset) public view returns (IERC20) { uint256 index = uint256(asset); if (index >= NUM_META_COINS) { revert IllegalArgument("Asset index out of bounds"); } return _metaPoolAssetCache[index]; } /// @notice Begins the 2-step process of setting the administrator. /// /// The caller must be the admin. Setting the pending timelock to the zero address will stop /// the process of setting a new timelock. /// /// @param value The value to set the pending timelock to. function setPendingAdmin(address value) external onlyAdmin { pendingAdmin = value; emit PendingAdminUpdated(value); } /// @notice Completes the 2-step process of setting the administrator. /// /// The pending admin must be set and the caller must be the pending admin. After this function /// is successfully executed, the admin will be set to the pending admin and the pending admin /// will be reset. function acceptAdmin() external { if (pendingAdmin == address(0)) { revert IllegalState("Pending admin unset"); } if (pendingAdmin != msg.sender) { revert Unauthorized("Not pending admin"); } admin = pendingAdmin; pendingAdmin = address(0); emit AdminUpdated(admin); emit PendingAdminUpdated(address(0)); } /// @notice Sets the operator. /// /// The caller must be the admin. /// /// @param value The value to set the admin to. function setOperator(address value) external onlyAdmin { operator = value; emit OperatorUpdated(value); } /// @notice Sets the reward receiver. /// /// @param value The value to set the reward receiver to. function setRewardReceiver(address value) external onlyAdmin { rewardReceiver = value; emit RewardReceiverUpdated(value); } /// @notice Sets the transmuter buffer. /// /// @param value The value to set the transmuter buffer to. function setTransmuterBuffer(address value) external onlyAdmin { transmuterBuffer = value; emit TransmuterBufferUpdated(value); } /// @notice Sets the slippage that will be tolerated when depositing and withdrawing 3pool /// assets. The slippage has a resolution of 6 decimals. /// /// The operator is allowed to set the slippage because it is a volatile parameter that may need /// fine adjustment in a short time window. /// /// @param value The value to set the slippage to. function setThreePoolSlippage(uint256 value) external onlyOperator { if (value > SLIPPAGE_PRECISION) { revert IllegalArgument("Slippage not in range"); } threePoolSlippage = value; emit ThreePoolSlippageUpdated(value); } /// @notice Sets the slippage that will be tolerated when depositing and withdrawing meta pool /// assets. The slippage has a resolution of 6 decimals. /// /// The operator is allowed to set the slippage because it is a volatile parameter that may need /// fine adjustment in a short time window. /// /// @param value The value to set the slippage to. function setMetaPoolSlippage(uint256 value) external onlyOperator { if (value > SLIPPAGE_PRECISION) { revert IllegalArgument("Slippage not in range"); } metaPoolSlippage = value; emit MetaPoolSlippageUpdated(value); } /// @notice Mints 3pool tokens with a combination of assets. /// /// @param amounts The amounts of the assets to deposit. /// /// @return minted The number of 3pool tokens minted. function mintThreePoolTokens( uint256[NUM_STABLE_COINS] calldata amounts ) external lock onlyOperator returns (uint256 minted) { return _mintThreePoolTokens(amounts); } /// @notice Mints 3pool tokens with an asset. /// /// @param asset The asset to deposit into the 3pool. /// @param amount The amount of the asset to deposit. /// /// @return minted The number of 3pool tokens minted. function mintThreePoolTokens( ThreePoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256 minted) { return _mintThreePoolTokens(asset, amount); } /// @notice Burns 3pool tokens to withdraw an asset. /// /// @param asset The asset to withdraw. /// @param amount The amount of 3pool tokens to burn. /// /// @return withdrawn The amount of the asset withdrawn from the pool. function burnThreePoolTokens( ThreePoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256 withdrawn) { return _burnThreePoolTokens(asset, amount); } /// @notice Mints meta pool tokens with a combination of assets. /// /// @param amounts The amounts of the assets to deposit. /// /// @return minted The number of meta pool tokens minted. function mintMetaPoolTokens( uint256[NUM_META_COINS] calldata amounts ) external lock onlyOperator returns (uint256 minted) { return _mintMetaPoolTokens(amounts); } /// @notice Mints meta pool tokens with an asset. /// /// @param asset The asset to deposit into the meta pool. /// @param amount The amount of the asset to deposit. /// /// @return minted The number of meta pool tokens minted. function mintMetaPoolTokens( MetaPoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256 minted) { return _mintMetaPoolTokens(asset, amount); } /// @notice Burns meta pool tokens to withdraw an asset. /// /// @param asset The asset to withdraw. /// @param amount The amount of meta pool tokens to burn. /// /// @return withdrawn The amount of the asset withdrawn from the pool. function burnMetaPoolTokens( MetaPoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256 withdrawn) { return _burnMetaPoolTokens(asset, amount); } /// @notice Deposits and stakes meta pool tokens into convex. /// /// @param amount The amount of meta pool tokens to deposit. /// /// @return success If the tokens were successfully deposited. function depositMetaPoolTokens( uint256 amount ) external lock onlyOperator returns (bool success) { return _depositMetaPoolTokens(amount); } /// @notice Withdraws and unwraps meta pool tokens from convex. /// /// @param amount The amount of meta pool tokens to withdraw. /// /// @return success If the tokens were successfully withdrawn. function withdrawMetaPoolTokens( uint256 amount ) external lock onlyOperator returns (bool success) { return _withdrawMetaPoolTokens(amount); } /// @notice Claims convex, curve, and auxiliary rewards. /// /// @return success If the claim was successful. function claimRewards() external lock onlyOperator returns (bool success) { success = convexRewards.getReward(); uint256 curveBalance = curveToken.balanceOf(address(this)); uint256 convexBalance = convexToken.balanceOf(address(this)); SafeERC20.safeTransfer(address(curveToken), rewardReceiver, curveBalance); SafeERC20.safeTransfer(address(convexToken), rewardReceiver, convexBalance); emit ClaimRewards(success, curveBalance, convexBalance); } /// @notice Flushes three pool assets into convex by minting 3pool tokens from the assets, /// minting meta pool tokens using the 3pool tokens, and then depositing the meta pool /// tokens into convex. /// /// This function is provided for ease of use. /// /// @param amounts The amounts of the 3pool assets to flush. /// /// @return The amount of meta pool tokens deposited into convex. function flush( uint256[NUM_STABLE_COINS] calldata amounts ) external lock onlyOperator returns (uint256) { uint256 mintedThreePoolTokens = _mintThreePoolTokens(amounts); uint256 mintedMetaPoolTokens = _mintMetaPoolTokens( MetaPoolAsset.THREE_POOL, mintedThreePoolTokens ); if (!_depositMetaPoolTokens(mintedMetaPoolTokens)) { revert IllegalState("Deposit into convex failed"); } return mintedMetaPoolTokens; } /// @notice Flushes a three pool asset into convex by minting 3pool tokens using the asset, /// minting meta pool tokens using the 3pool tokens, and then depositing the meta pool /// tokens into convex. /// /// This function is provided for ease of use. /// /// @param asset The 3pool asset to flush. /// @param amount The amount of the 3pool asset to flush. /// /// @return The amount of meta pool tokens deposited into convex. function flush( ThreePoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256) { uint256 mintedThreePoolTokens = _mintThreePoolTokens(asset, amount); uint256 mintedMetaPoolTokens = _mintMetaPoolTokens( MetaPoolAsset.THREE_POOL, mintedThreePoolTokens ); if (!_depositMetaPoolTokens(mintedMetaPoolTokens)) { revert IllegalState("Deposit into convex failed"); } return mintedMetaPoolTokens; } /// @notice Recalls a three pool asset into reserves by withdrawing meta pool tokens from /// convex, burning the meta pool tokens for 3pool tokens, and then burning the 3pool /// tokens for an asset. /// /// This function is provided for ease of use. /// /// @param asset The 3pool asset to recall. /// @param amount The amount of the meta pool tokens to withdraw from convex and burn. /// /// @return The amount of the 3pool asset recalled. function recall( ThreePoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256) { if (!_withdrawMetaPoolTokens(amount)) { revert IllegalState("Withdraw from convex failed"); } uint256 withdrawnThreePoolTokens = _burnMetaPoolTokens(MetaPoolAsset.THREE_POOL, amount); return _burnThreePoolTokens(asset, withdrawnThreePoolTokens); } /// @notice Reclaims a three pool asset to the transmuter buffer. /// /// @param asset The 3pool asset to reclaim. /// @param amount The amount to reclaim. function reclaimThreePoolAsset(ThreePoolAsset asset, uint256 amount) public lock onlyAdmin { IERC20 token = getTokenForThreePoolAsset(asset); SafeERC20.safeTransfer(address(token), transmuterBuffer, amount); IERC20TokenReceiver(transmuterBuffer).onERC20Received(address(token), amount); emit ReclaimThreePoolAsset(asset, amount); } /// @notice Sweeps a token out of the contract to the admin. /// /// @param token The token to sweep. /// @param amount The amount of the token to sweep. function sweep(address token, uint256 amount) external lock onlyAdmin { SafeERC20.safeTransfer(address(token), msg.sender, amount); } /// @inheritdoc IERC20TokenReceiver /// /// @dev This function is required in order to receive tokens from the conduit. function onERC20Received(address token, uint256 value) external { /* noop */ } /// @dev Gets the amount of convex that will be minted for an amount of curve tokens. /// /// @param amountCurve The amount of curve tokens. /// /// @return The amount of convex tokens. function _getEarnedConvex(uint256 amountCurve) internal view returns (uint256) { uint256 supply = convexToken.totalSupply(); uint256 cliff = supply / convexToken.reductionPerCliff(); uint256 totalCliffs = convexToken.totalCliffs(); if (cliff >= totalCliffs) return 0; uint256 reduction = totalCliffs - cliff; uint256 earned = amountCurve * reduction / totalCliffs; uint256 available = convexToken.maxSupply() - supply; return earned > available ? available : earned; } /// @dev Mints 3pool tokens with a combination of assets. /// /// @param amounts The amounts of the assets to deposit. /// /// @return minted The number of 3pool tokens minted. function _mintThreePoolTokens( uint256[NUM_STABLE_COINS] calldata amounts ) internal returns (uint256 minted) { IERC20[NUM_STABLE_COINS] memory tokens = _threePoolAssetCache; IERC20 threePoolToken = getTokenForMetaPoolAsset(MetaPoolAsset.THREE_POOL); uint256 threePoolDecimals = SafeERC20.expectDecimals(address(threePoolToken)); uint256 normalizedTotal = 0; for (uint256 i = 0; i < NUM_STABLE_COINS; i++) { if (amounts[i] == 0) continue; uint256 tokenDecimals = SafeERC20.expectDecimals(address(tokens[i])); uint256 missingDecimals = threePoolDecimals - tokenDecimals; normalizedTotal += amounts[i] * 10**missingDecimals; // For assets like USDT, the approval must be first set to zero before updating it. SafeERC20.safeApprove(address(tokens[i]), address(threePool), 0); SafeERC20.safeApprove(address(tokens[i]), address(threePool), amounts[i]); } // Calculate what the normalized value of the tokens is. uint256 expectedOutput = normalizedTotal * CURVE_PRECISION / threePool.get_virtual_price(); // Calculate the minimum amount of 3pool lp tokens that we are expecting out when // adding liquidity for all of the assets. This value is based off the optimistic // assumption that one of each token is approximately equal to one 3pool lp token. uint256 minimumMintAmount = expectedOutput * threePoolSlippage / SLIPPAGE_PRECISION; // Record the amount of 3pool lp tokens that we start with before adding liquidity // so that we can determine how many we minted. uint256 startingBalance = threePoolToken.balanceOf(address(this)); // Add the liquidity to the pool. threePool.add_liquidity(amounts, minimumMintAmount); // Calculate how many 3pool lp tokens were minted. minted = threePoolToken.balanceOf(address(this)) - startingBalance; emit MintThreePoolTokens(amounts, minted); } /// @dev Mints 3pool tokens with an asset. /// /// @param asset The asset to deposit into the 3pool. /// @param amount The amount of the asset to deposit. /// /// @return minted The number of 3pool tokens minted. function _mintThreePoolTokens( ThreePoolAsset asset, uint256 amount ) internal returns (uint256 minted) { IERC20 token = getTokenForThreePoolAsset(asset); IERC20 threePoolToken = getTokenForMetaPoolAsset(MetaPoolAsset.THREE_POOL); uint256 threePoolDecimals = SafeERC20.expectDecimals(address(threePoolToken)); uint256 missingDecimals = threePoolDecimals - SafeERC20.expectDecimals(address(token)); uint256[NUM_STABLE_COINS] memory amounts; amounts[uint256(asset)] = amount; // Calculate the minimum amount of 3pool lp tokens that we are expecting out when // adding single sided liquidity. This value is based off the optimistic assumption that // one of each token is approximately equal to one 3pool lp token. uint256 normalizedAmount = amount * 10**missingDecimals; uint256 expectedOutput = normalizedAmount * CURVE_PRECISION / threePool.get_virtual_price(); uint256 minimumMintAmount = expectedOutput * threePoolSlippage / SLIPPAGE_PRECISION; // Record the amount of 3pool lp tokens that we start with before adding liquidity // so that we can determine how many we minted. uint256 startingBalance = threePoolToken.balanceOf(address(this)); // For assets like USDT, the approval must be first set to zero before updating it. SafeERC20.safeApprove(address(token), address(threePool), 0); SafeERC20.safeApprove(address(token), address(threePool), amount); // Add the liquidity to the pool. threePool.add_liquidity(amounts, minimumMintAmount); // Calculate how many 3pool lp tokens were minted. minted = threePoolToken.balanceOf(address(this)) - startingBalance; emit MintThreePoolTokens(asset, amount, minted); } /// @dev Burns 3pool tokens to withdraw an asset. /// /// @param asset The asset to withdraw. /// @param amount The amount of 3pool tokens to burn. /// /// @return withdrawn The amount of the asset withdrawn from the pool. function _burnThreePoolTokens( ThreePoolAsset asset, uint256 amount ) internal returns (uint256 withdrawn) { IERC20 token = getTokenForThreePoolAsset(asset); IERC20 threePoolToken = getTokenForMetaPoolAsset(MetaPoolAsset.THREE_POOL); uint256 index = uint256(asset); uint256 threePoolDecimals = SafeERC20.expectDecimals(address(threePoolToken)); uint256 missingDecimals = threePoolDecimals - SafeERC20.expectDecimals(address(token)); // Calculate the minimum amount of underlying tokens that we are expecting out when // removing single sided liquidity. This value is based off the optimistic assumption that // one of each token is approximately equal to one 3pool lp token. uint256 normalizedAmount = amount * threePoolSlippage / SLIPPAGE_PRECISION; uint256 expectedOutput = normalizedAmount * threePool.get_virtual_price() / CURVE_PRECISION; uint256 minimumAmountOut = expectedOutput / 10**missingDecimals; // Record the amount of underlying tokens that we start with before removing liquidity // so that we can determine how many we withdrew from the pool. uint256 startingBalance = token.balanceOf(address(this)); SafeERC20.safeApprove(address(threePoolToken), address(threePool), 0); SafeERC20.safeApprove(address(threePoolToken), address(threePool), amount); // Remove the liquidity from the pool. threePool.remove_liquidity_one_coin(amount, int128(uint128(index)), minimumAmountOut); // Calculate how many underlying tokens that were withdrawn. withdrawn = token.balanceOf(address(this)) - startingBalance; emit BurnThreePoolTokens(asset, amount, withdrawn); } /// @dev Mints meta pool tokens with a combination of assets. /// /// @param amounts The amounts of the assets to deposit. /// /// @return minted The number of meta pool tokens minted. function _mintMetaPoolTokens( uint256[NUM_META_COINS] calldata amounts ) internal returns (uint256 minted) { IERC20[NUM_META_COINS] memory tokens = _metaPoolAssetCache; uint256 total = 0; for (uint256 i = 0; i < NUM_META_COINS; i++) { if (amounts[i] == 0) continue; total += amounts[i]; // For assets like USDT, the approval must be first set to zero before updating it. SafeERC20.safeApprove(address(tokens[i]), address(metaPool), 0); SafeERC20.safeApprove(address(tokens[i]), address(metaPool), amounts[i]); } // Calculate the minimum amount of 3pool lp tokens that we are expecting out when // adding liquidity for all of the assets. This value is based off the optimistic // assumption that one of each token is approximately equal to one 3pool lp token. uint256 expectedOutput = total * CURVE_PRECISION / metaPool.get_virtual_price(); uint256 minimumMintAmount = expectedOutput * metaPoolSlippage / SLIPPAGE_PRECISION; // Add the liquidity to the pool. minted = metaPool.add_liquidity(amounts, minimumMintAmount); emit MintMetaPoolTokens(amounts, minted); } /// @dev Mints meta pool tokens with an asset. /// /// @param asset The asset to deposit into the meta pool. /// @param amount The amount of the asset to deposit. /// /// @return minted The number of meta pool tokens minted. function _mintMetaPoolTokens( MetaPoolAsset asset, uint256 amount ) internal returns (uint256 minted) { IERC20 token = getTokenForMetaPoolAsset(asset); uint256[NUM_META_COINS] memory amounts; amounts[uint256(asset)] = amount; // Calculate the minimum amount of 3pool lp tokens that we are expecting out when // adding single sided liquidity. This value is based off the optimistic assumption that uint256 minimumMintAmount = amount * metaPoolSlippage / SLIPPAGE_PRECISION; // For assets like USDT, the approval must be first set to zero before updating it. SafeERC20.safeApprove(address(token), address(metaPool), 0); SafeERC20.safeApprove(address(token), address(metaPool), amount); // Add the liquidity to the pool. minted = metaPool.add_liquidity(amounts, minimumMintAmount); emit MintMetaPoolTokens(asset, amount, minted); } /// @dev Burns meta pool tokens to withdraw an asset. /// /// @param asset The asset to withdraw. /// @param amount The amount of meta pool tokens to burn. /// /// @return withdrawn The amount of the asset withdrawn from the pool. function _burnMetaPoolTokens( MetaPoolAsset asset, uint256 amount ) internal returns (uint256 withdrawn) { uint256 index = uint256(asset); // Calculate the minimum amount of the meta pool asset that we are expecting out when // removing single sided liquidity. This value is based off the optimistic assumption that // one of each token is approximately equal to one meta pool lp token. uint256 expectedOutput = amount * metaPool.get_virtual_price() / CURVE_PRECISION; uint256 minimumAmountOut = expectedOutput * metaPoolSlippage / SLIPPAGE_PRECISION; // Remove the liquidity from the pool. withdrawn = metaPool.remove_liquidity_one_coin( amount, int128(uint128(index)), minimumAmountOut ); emit BurnMetaPoolTokens(asset, amount, withdrawn); } /// @dev Deposits and stakes meta pool tokens into convex. /// /// @param amount The amount of meta pool tokens to deposit. /// /// @return success If the tokens were successfully deposited. function _depositMetaPoolTokens(uint256 amount) internal returns (bool success) { SafeERC20.safeApprove(address(metaPool), address(convexBooster), 0); SafeERC20.safeApprove(address(metaPool), address(convexBooster), amount); success = convexBooster.deposit(convexPoolId, amount, true /* always stake into rewards */); emit DepositMetaPoolTokens(amount, success); } /// @dev Withdraws and unwraps meta pool tokens from convex. /// /// @param amount The amount of meta pool tokens to withdraw. /// /// @return success If the tokens were successfully withdrawn. function _withdrawMetaPoolTokens(uint256 amount) internal returns (bool success) { success = convexRewards.withdrawAndUnwrap(amount, false /* never claim */); emit WithdrawMetaPoolTokens(amount, success); } /// @dev Claims convex, curve, and auxiliary rewards. /// /// @return success If the claim was successful. function _claimRewards() internal returns (bool success) { success = convexRewards.getReward(); uint256 curveBalance = curveToken.balanceOf(address(this)); uint256 convexBalance = convexToken.balanceOf(address(this)); SafeERC20.safeTransfer(address(curveToken), rewardReceiver, curveBalance); SafeERC20.safeTransfer(address(convexToken), rewardReceiver, convexBalance); emit ClaimRewards(success, curveBalance, convexBalance); } /// @dev Gets the minimum of two integers. /// /// @param x The first integer. /// @param y The second integer. /// /// @return The minimum value. function min(uint256 x , uint256 y) private pure returns (uint256) { return x > y ? y : x; } /// @dev Gets the absolute value of the difference of two integers. /// /// @param x The first integer. /// @param y The second integer. /// /// @return The absolute value. function abs(uint256 x , uint256 y) private pure returns (uint256) { return x > y ? x - y : y - x; } }
Reclaims a three pool asset to the transmuter buffer. asset The 3pool asset to reclaim. amount The amount to reclaim.
function reclaimThreePoolAsset(ThreePoolAsset asset, uint256 amount) public lock onlyAdmin { IERC20 token = getTokenForThreePoolAsset(asset); SafeERC20.safeTransfer(address(token), transmuterBuffer, amount); IERC20TokenReceiver(transmuterBuffer).onERC20Received(address(token), amount); emit ReclaimThreePoolAsset(asset, amount); }
13,997,980
./full_match/1313161554/0x90C6B69383695b4Dc4125ca010C61f78dff93fb0/sources/contracts/UTURewardsInterface.sol
UTU Coin Rewards Interface This interface defines the public functions and events that are used for claiming UTU Coin ($UTU) rewards./
interface UTURewardsInterface { function claimRewards() external; event RewardUTUCoin(address indexed _to, uint _value); event ClaimUTURewards(address indexed _by, uint _value); }
13,234,615
./full_match/80001/0x428d527d80255562131153A5D4BDF036bd73741d/sources/project_/contracts/Roulette.sol
enables the contract to be used
function toggleOn() public override(GameManager) onlyRole(GAME_MANAGER_ROLE) { super.toggleOn(); }
5,587,607
./full_match/1/0xAD250345078Aba5D052c1a8040FD1C1595f4eA00/sources/src/core/auctions/simple/SimpleSettlementBase.sol
Settles a single bid revokes access to counterparty (msg.sender) after complete _bid is the signed data type containing bid information _collateralIds array of grappa ids for erc20 tokens needed to collateralize options _amounts array of (counterparty) deposit amounts for each collateral + premium (if applicable)/
function settle(Bid calldata _bid, uint8[] calldata _collateralIds, uint256[] calldata _amounts) external virtual {}
17,153,193
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./VeJoeToken.sol"; /// @title Vote Escrow Joe Staking /// @author Trader Joe /// @notice Stake JOE to earn veJOE, which you can use to earn higher farm yields and gain /// voting power. Note that unstaking any amount of JOE will burn all of your existing veJOE. contract VeJoeStaking is Initializable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice Info for each user /// `balance`: Amount of JOE currently staked by user /// `rewardDebt`: The reward debt of the user /// `lastClaimTimestamp`: The timestamp of user's last claim or withdraw /// `speedUpEndTimestamp`: The timestamp when user stops receiving speed up benefits, or /// zero if user is not currently receiving speed up benefits struct UserInfo { uint256 balance; uint256 rewardDebt; uint256 lastClaimTimestamp; uint256 speedUpEndTimestamp; /** * @notice We do some fancy math here. Basically, any point in time, the amount of veJOE * entitled to a user but is pending to be distributed is: * * pendingReward = pendingBaseReward + pendingSpeedUpReward * * pendingBaseReward = (user.balance * accVeJoePerShare) - user.rewardDebt * * if user.speedUpEndTimestamp != 0: * speedUpCeilingTimestamp = min(block.timestamp, user.speedUpEndTimestamp) * speedUpSecondsElapsed = speedUpCeilingTimestamp - user.lastClaimTimestamp * pendingSpeedUpReward = speedUpSecondsElapsed * user.balance * speedUpVeJoePerSharePerSec * else: * pendingSpeedUpReward = 0 */ } IERC20Upgradeable public joe; VeJoeToken public veJoe; /// @notice The maximum ratio of veJOE to staked JOE /// For example, if user has `n` JOE staked, they can own a maximum of `n * maxCap` veJOE. uint256 public maxCap; /// @notice The upper limit of `maxCap` uint256 public upperLimitMaxCap; /// @notice The accrued veJoe per share, scaled to `ACC_VEJOE_PER_SHARE_PRECISION` uint256 public accVeJoePerShare; /// @notice Precision of `accVeJoePerShare` uint256 public ACC_VEJOE_PER_SHARE_PRECISION; /// @notice The last time that the reward variables were updated uint256 public lastRewardTimestamp; /// @notice veJOE per sec per JOE staked, scaled to `VEJOE_PER_SHARE_PER_SEC_PRECISION` uint256 public veJoePerSharePerSec; /// @notice Speed up veJOE per sec per JOE staked, scaled to `VEJOE_PER_SHARE_PER_SEC_PRECISION` uint256 public speedUpVeJoePerSharePerSec; /// @notice The upper limit of `veJoePerSharePerSec` and `speedUpVeJoePerSharePerSec` uint256 public upperLimitVeJoePerSharePerSec; /// @notice Precision of `veJoePerSharePerSec` uint256 public VEJOE_PER_SHARE_PER_SEC_PRECISION; /// @notice Percentage of user's current staked JOE user has to deposit in order to start /// receiving speed up benefits, in parts per 100. /// @dev Specifically, user has to deposit at least `speedUpThreshold/100 * userStakedJoe` JOE. /// The only exception is the user will also receive speed up benefits if they are depositing /// with zero balance uint256 public speedUpThreshold; /// @notice The length of time a user receives speed up benefits uint256 public speedUpDuration; mapping(address => UserInfo) public userInfos; event Claim(address indexed user, uint256 amount); event Deposit(address indexed user, uint256 amount); event UpdateMaxCap(address indexed user, uint256 maxCap); event UpdateRewardVars(uint256 lastRewardTimestamp, uint256 accVeJoePerShare); event UpdateSpeedUpThreshold(address indexed user, uint256 speedUpThreshold); event UpdateVeJoePerSharePerSec(address indexed user, uint256 veJoePerSharePerSec); event Withdraw(address indexed user, uint256 amount); /// @notice Initialize with needed parameters /// @param _joe Address of the JOE token contract /// @param _veJoe Address of the veJOE token contract /// @param _veJoePerSharePerSec veJOE per sec per JOE staked, scaled to `VEJOE_PER_SHARE_PER_SEC_PRECISION` /// @param _speedUpVeJoePerSharePerSec Similar to `_veJoePerSharePerSec` but for speed up /// @param _speedUpThreshold Percentage of total staked JOE user has to deposit receive speed up /// @param _speedUpDuration Length of time a user receives speed up benefits /// @param _maxCap The maximum amount of veJOE received per JOE staked function initialize( IERC20Upgradeable _joe, VeJoeToken _veJoe, uint256 _veJoePerSharePerSec, uint256 _speedUpVeJoePerSharePerSec, uint256 _speedUpThreshold, uint256 _speedUpDuration, uint256 _maxCap ) public initializer { require(address(_joe) != address(0), "VeJoeStaking: unexpected zero address for _joe"); require(address(_veJoe) != address(0), "VeJoeStaking: unexpected zero address for _veJoe"); upperLimitVeJoePerSharePerSec = 1e36; require( _veJoePerSharePerSec <= upperLimitVeJoePerSharePerSec, "VeJoeStaking: expected _veJoePerSharePerSec to be <= 1e36" ); require( _speedUpVeJoePerSharePerSec <= upperLimitVeJoePerSharePerSec, "VeJoeStaking: expected _speedUpVeJoePerSharePerSec to be <= 1e36" ); require( _speedUpThreshold != 0 && _speedUpThreshold <= 100, "VeJoeStaking: expected _speedUpThreshold to be > 0 and <= 100" ); require(_speedUpDuration <= 365 days, "VeJoeStaking: expected _speedUpDuration to be <= 365 days"); upperLimitMaxCap = 100000; require( _maxCap != 0 && _maxCap <= upperLimitMaxCap, "VeJoeStaking: expected _maxCap to be non-zero and <= 100000" ); __Ownable_init(); maxCap = _maxCap; speedUpThreshold = _speedUpThreshold; speedUpDuration = _speedUpDuration; joe = _joe; veJoe = _veJoe; veJoePerSharePerSec = _veJoePerSharePerSec; speedUpVeJoePerSharePerSec = _speedUpVeJoePerSharePerSec; lastRewardTimestamp = block.timestamp; ACC_VEJOE_PER_SHARE_PRECISION = 1e18; VEJOE_PER_SHARE_PER_SEC_PRECISION = 1e18; } /// @notice Set maxCap /// @param _maxCap The new maxCap function setMaxCap(uint256 _maxCap) external onlyOwner { require(_maxCap > maxCap, "VeJoeStaking: expected new _maxCap to be greater than existing maxCap"); require( _maxCap != 0 && _maxCap <= upperLimitMaxCap, "VeJoeStaking: expected new _maxCap to be non-zero and <= 100000" ); maxCap = _maxCap; emit UpdateMaxCap(msg.sender, _maxCap); } /// @notice Set veJoePerSharePerSec /// @param _veJoePerSharePerSec The new veJoePerSharePerSec function setVeJoePerSharePerSec(uint256 _veJoePerSharePerSec) external onlyOwner { require( _veJoePerSharePerSec <= upperLimitVeJoePerSharePerSec, "VeJoeStaking: expected _veJoePerSharePerSec to be <= 1e36" ); updateRewardVars(); veJoePerSharePerSec = _veJoePerSharePerSec; emit UpdateVeJoePerSharePerSec(msg.sender, _veJoePerSharePerSec); } /// @notice Set speedUpThreshold /// @param _speedUpThreshold The new speedUpThreshold function setSpeedUpThreshold(uint256 _speedUpThreshold) external onlyOwner { require( _speedUpThreshold != 0 && _speedUpThreshold <= 100, "VeJoeStaking: expected _speedUpThreshold to be > 0 and <= 100" ); speedUpThreshold = _speedUpThreshold; emit UpdateSpeedUpThreshold(msg.sender, _speedUpThreshold); } /// @notice Deposits JOE to start staking for veJOE. Note that any pending veJOE /// will also be claimed in the process. /// @param _amount The amount of JOE to deposit function deposit(uint256 _amount) external { require(_amount > 0, "VeJoeStaking: expected deposit amount to be greater than zero"); updateRewardVars(); UserInfo storage userInfo = userInfos[msg.sender]; if (_getUserHasNonZeroBalance(msg.sender)) { // Transfer to the user their pending veJOE before updating their UserInfo _claim(); // We need to update user's `lastClaimTimestamp` to now to prevent // passive veJOE accrual if user hit their max cap. userInfo.lastClaimTimestamp = block.timestamp; uint256 userStakedJoe = userInfo.balance; // User is eligible for speed up benefits if `_amount` is at least // `speedUpThreshold / 100 * userStakedJoe` if (_amount.mul(100) >= speedUpThreshold.mul(userStakedJoe)) { userInfo.speedUpEndTimestamp = block.timestamp.add(speedUpDuration); } } else { // If user is depositing with zero balance, they will automatically // receive speed up benefits userInfo.speedUpEndTimestamp = block.timestamp.add(speedUpDuration); userInfo.lastClaimTimestamp = block.timestamp; } userInfo.balance = userInfo.balance.add(_amount); userInfo.rewardDebt = accVeJoePerShare.mul(userInfo.balance).div(ACC_VEJOE_PER_SHARE_PRECISION); joe.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); } /// @notice Withdraw staked JOE. Note that unstaking any amount of JOE means you will /// lose all of your current veJOE. /// @param _amount The amount of JOE to unstake function withdraw(uint256 _amount) external { require(_amount > 0, "VeJoeStaking: expected withdraw amount to be greater than zero"); UserInfo storage userInfo = userInfos[msg.sender]; require( userInfo.balance >= _amount, "VeJoeStaking: cannot withdraw greater amount of JOE than currently staked" ); updateRewardVars(); // Note that we don't need to claim as the user's veJOE balance will be reset to 0 userInfo.balance = userInfo.balance.sub(_amount); userInfo.rewardDebt = accVeJoePerShare.mul(userInfo.balance).div(ACC_VEJOE_PER_SHARE_PRECISION); userInfo.lastClaimTimestamp = block.timestamp; userInfo.speedUpEndTimestamp = 0; // Burn the user's current veJOE balance veJoe.burnFrom(msg.sender, veJoe.balanceOf(msg.sender)); // Send user their requested amount of staked JOE joe.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } /// @notice Claim any pending veJOE function claim() external { require(_getUserHasNonZeroBalance(msg.sender), "VeJoeStaking: cannot claim veJOE when no JOE is staked"); updateRewardVars(); _claim(); } /// @notice Get the pending amount of veJOE for a given user /// @param _user The user to lookup /// @return The number of pending veJOE tokens for `_user` function getPendingVeJoe(address _user) public view returns (uint256) { if (!_getUserHasNonZeroBalance(_user)) { return 0; } UserInfo memory user = userInfos[_user]; // Calculate amount of pending base veJOE uint256 _accVeJoePerShare = accVeJoePerShare; uint256 secondsElapsed = block.timestamp.sub(lastRewardTimestamp); if (secondsElapsed > 0) { _accVeJoePerShare = _accVeJoePerShare.add( secondsElapsed.mul(veJoePerSharePerSec).mul(ACC_VEJOE_PER_SHARE_PRECISION).div( VEJOE_PER_SHARE_PER_SEC_PRECISION ) ); } uint256 pendingBaseVeJoe = _accVeJoePerShare.mul(user.balance).div(ACC_VEJOE_PER_SHARE_PRECISION).sub( user.rewardDebt ); // Calculate amount of pending speed up veJOE uint256 pendingSpeedUpVeJoe; if (user.speedUpEndTimestamp != 0) { uint256 speedUpCeilingTimestamp = block.timestamp > user.speedUpEndTimestamp ? user.speedUpEndTimestamp : block.timestamp; uint256 speedUpSecondsElapsed = speedUpCeilingTimestamp.sub(user.lastClaimTimestamp); uint256 speedUpAccVeJoePerShare = speedUpSecondsElapsed.mul(speedUpVeJoePerSharePerSec); pendingSpeedUpVeJoe = speedUpAccVeJoePerShare.mul(user.balance).div(VEJOE_PER_SHARE_PER_SEC_PRECISION); } uint256 pendingVeJoe = pendingBaseVeJoe.add(pendingSpeedUpVeJoe); // Get the user's current veJOE balance and maximum veJOE they can hold uint256 userVeJoeBalance = veJoe.balanceOf(_user); uint256 userMaxVeJoeCap = user.balance.mul(maxCap); if (userVeJoeBalance >= userMaxVeJoeCap) { // User already holds maximum amount of veJOE so there is no pending veJOE return 0; } else if (userVeJoeBalance.add(pendingVeJoe) > userMaxVeJoeCap) { return userMaxVeJoeCap.sub(userVeJoeBalance); } else { return pendingVeJoe; } } /// @notice Update reward variables function updateRewardVars() public { if (block.timestamp <= lastRewardTimestamp) { return; } if (joe.balanceOf(address(this)) == 0) { lastRewardTimestamp = block.timestamp; return; } uint256 secondsElapsed = block.timestamp.sub(lastRewardTimestamp); accVeJoePerShare = accVeJoePerShare.add( secondsElapsed.mul(veJoePerSharePerSec).mul(ACC_VEJOE_PER_SHARE_PRECISION).div( VEJOE_PER_SHARE_PER_SEC_PRECISION ) ); lastRewardTimestamp = block.timestamp; emit UpdateRewardVars(lastRewardTimestamp, accVeJoePerShare); } /// @notice Checks to see if a given user currently has staked JOE /// @param _user The user address to check /// @return Whether `_user` currently has staked JOE function _getUserHasNonZeroBalance(address _user) private view returns (bool) { return userInfos[_user].balance > 0; } /// @dev Helper to claim any pending veJOE function _claim() private { uint256 veJoeToClaim = getPendingVeJoe(msg.sender); UserInfo storage userInfo = userInfos[msg.sender]; userInfo.rewardDebt = accVeJoePerShare.mul(userInfo.balance).div(ACC_VEJOE_PER_SHARE_PRECISION); // If user's speed up period has ended, reset `speedUpEndTimestamp` to 0 if (userInfo.speedUpEndTimestamp != 0 && block.timestamp >= userInfo.speedUpEndTimestamp) { userInfo.speedUpEndTimestamp = 0; } if (veJoeToClaim > 0) { userInfo.lastClaimTimestamp = block.timestamp; veJoe.mint(msg.sender, veJoeToClaim); emit Claim(msg.sender, veJoeToClaim); } } }
Deposits JOE to start staking for veJOE. Note that any pending veJOE will also be claimed in the process. _amount The amount of JOE to deposit Transfer to the user their pending veJOE before updating their UserInfo We need to update user's `lastClaimTimestamp` to now to prevent passive veJOE accrual if user hit their max cap. User is eligible for speed up benefits if `_amount` is at least `speedUpThreshold / 100 userStakedJoe`
function deposit(uint256 _amount) external { require(_amount > 0, "VeJoeStaking: expected deposit amount to be greater than zero"); updateRewardVars(); UserInfo storage userInfo = userInfos[msg.sender]; if (_getUserHasNonZeroBalance(msg.sender)) { _claim(); userInfo.lastClaimTimestamp = block.timestamp; uint256 userStakedJoe = userInfo.balance; if (_amount.mul(100) >= speedUpThreshold.mul(userStakedJoe)) { userInfo.speedUpEndTimestamp = block.timestamp.add(speedUpDuration); } userInfo.lastClaimTimestamp = block.timestamp; } userInfo.balance = userInfo.balance.add(_amount); userInfo.rewardDebt = accVeJoePerShare.mul(userInfo.balance).div(ACC_VEJOE_PER_SHARE_PRECISION); joe.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); }
15,826,600
//Address: 0x04f062809b244e37e7fdc21d9409469c989c2342 //Contract name: Joyso //Balance: 230.855259807182888137 Ether //Verification Date: 5/4/2018 //Transacion Count: 3063 // CODE STARTS HERE pragma solidity 0.4.19; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title 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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title Migratable * @dev an interface for joyso to migrate to the new version */ contract Migratable { function migrate(address user, uint256 amount, address tokenAddr) external payable returns (bool); } /** * @title JoysoDataDecoder * @author Will, Emn178 * @notice decode the joyso compressed data */ contract JoysoDataDecoder { function decodeOrderUserId(uint256 data) internal pure returns (uint256) { return data & 0x00000000000000000000000000000000000000000000000000000000ffffffff; } function retrieveV(uint256 data) internal pure returns (uint256) { // [24..24] v 0:27 1:28 return data & 0x000000000000000000000000f000000000000000000000000000000000000000 == 0 ? 27 : 28; } } /** * @title Joyso * @notice joyso main contract * @author Will, Emn178 */ contract Joyso is Ownable, JoysoDataDecoder { using SafeMath for uint256; uint256 private constant USER_MASK = 0x00000000000000000000000000000000000000000000000000000000ffffffff; uint256 private constant PAYMENT_METHOD_MASK = 0x00000000000000000000000f0000000000000000000000000000000000000000; uint256 private constant WITHDRAW_TOKEN_MASK = 0x0000000000000000000000000000000000000000000000000000ffff00000000; uint256 private constant V_MASK = 0x000000000000000000000000f000000000000000000000000000000000000000; uint256 private constant TOKEN_SELL_MASK = 0x000000000000000000000000000000000000000000000000ffff000000000000; uint256 private constant TOKEN_BUY_MASK = 0x0000000000000000000000000000000000000000000000000000ffff00000000; uint256 private constant SIGN_MASK = 0xffffffffffffffffffffffff0000000000000000000000000000000000000000; uint256 private constant MATCH_SIGN_MASK = 0xfffffffffffffffffffffff00000000000000000000000000000000000000000; uint256 private constant TOKEN_JOY_PRICE_MASK = 0x0000000000000000000000000fffffffffffffffffffffff0000000000000000; uint256 private constant JOY_PRICE_MASK = 0x0000000000000000fffffff00000000000000000000000000000000000000000; uint256 private constant IS_BUY_MASK = 0x00000000000000000000000f0000000000000000000000000000000000000000; uint256 private constant TAKER_FEE_MASK = 0x00000000ffff0000000000000000000000000000000000000000000000000000; uint256 private constant MAKER_FEE_MASK = 0x000000000000ffff000000000000000000000000000000000000000000000000; uint256 private constant PAY_BY_TOKEN = 0x0000000000000000000000020000000000000000000000000000000000000000; uint256 private constant PAY_BY_JOY = 0x0000000000000000000000010000000000000000000000000000000000000000; uint256 private constant ORDER_ISBUY = 0x0000000000000000000000010000000000000000000000000000000000000000; mapping (address => mapping (address => uint256)) private balances; mapping (address => uint256) public userLock; mapping (address => uint256) public userNonce; mapping (bytes32 => uint256) public orderFills; mapping (bytes32 => bool) public usedHash; mapping (address => bool) public isAdmin; mapping (uint256 => address) public tokenId2Address; mapping (uint256 => address) public userId2Address; mapping (address => uint256) public userAddress2Id; mapping (address => uint256) public tokenAddress2Id; address public joysoWallet; address public joyToken; uint256 public lockPeriod = 30 days; uint256 public userCount; bool public tradeEventEnabled = true; modifier onlyAdmin { require(msg.sender == owner || isAdmin[msg.sender]); _; } //events event Deposit(address token, address user, uint256 amount, uint256 balance); event Withdraw(address token, address user, uint256 amount, uint256 balance); event NewUser(address user, uint256 id); event Lock(address user, uint256 timeLock); // for debug event TradeSuccess(address user, uint256 baseAmount, uint256 tokenAmount, bool isBuy, uint256 fee); function Joyso(address _joysoWallet, address _joyToken) public { joysoWallet = _joysoWallet; addUser(_joysoWallet); joyToken = _joyToken; tokenAddress2Id[joyToken] = 1; tokenAddress2Id[0] = 0; // ether address is Id 0 tokenId2Address[0] = 0; tokenId2Address[1] = joyToken; } /** * @notice deposit token into the contract * @notice Be sure to Approve the contract to move your erc20 token * @param token The address of deposited token * @param amount The amount of token to deposit */ function depositToken(address token, uint256 amount) external { require(amount > 0); require(tokenAddress2Id[token] != 0); addUser(msg.sender); require(ERC20(token).transferFrom(msg.sender, this, amount)); balances[token][msg.sender] = balances[token][msg.sender].add(amount); Deposit( token, msg.sender, amount, balances[token][msg.sender] ); } /** * @notice deposit Ether into the contract */ function depositEther() external payable { require(msg.value > 0); addUser(msg.sender); balances[0][msg.sender] = balances[0][msg.sender].add(msg.value); Deposit( 0, msg.sender, msg.value, balances[0][msg.sender] ); } /** * @notice withdraw funds directly from contract * @notice must claim by lockme first, after a period of time it would be valid * @param token The address of withdrawed token, using address(0) to withdraw Ether * @param amount The amount of token to withdraw */ function withdraw(address token, uint256 amount) external { require(amount > 0); require(getTime() > userLock[msg.sender] && userLock[msg.sender] != 0); balances[token][msg.sender] = balances[token][msg.sender].sub(amount); if (token == 0) { msg.sender.transfer(amount); } else { require(ERC20(token).transfer(msg.sender, amount)); } Withdraw( token, msg.sender, amount, balances[token][msg.sender] ); } /** * @notice This function is used to claim to withdraw the funds * @notice The matching server will automaticlly remove all un-touched orders * @notice After a period of time, the claimed user can withdraw funds directly from contract without admins involved. */ function lockMe() external { require(userAddress2Id[msg.sender] != 0); userLock[msg.sender] = getTime() + lockPeriod; Lock(msg.sender, userLock[msg.sender]); } /** * @notice This function is used to revoke the claim of lockMe */ function unlockMe() external { require(userAddress2Id[msg.sender] != 0); userLock[msg.sender] = 0; Lock(msg.sender, 0); } /** * @notice set tradeEventEnabled, only owner * @param enabled Set tradeEventEnabled if enabled */ function setTradeEventEnabled(bool enabled) external onlyOwner { tradeEventEnabled = enabled; } /** * @notice add/remove a address to admin list, only owner * @param admin The address of the admin * @param isAdd Set the address's status in admin list */ function addToAdmin(address admin, bool isAdd) external onlyOwner { isAdmin[admin] = isAdd; } /** * @notice collect the fee to owner's address, only owner */ function collectFee(address token) external onlyOwner { uint256 amount = balances[token][joysoWallet]; require(amount > 0); balances[token][joysoWallet] = 0; if (token == 0) { msg.sender.transfer(amount); } else { require(ERC20(token).transfer(msg.sender, amount)); } Withdraw( token, joysoWallet, amount, 0 ); } /** * @notice change lock period, only owner * @dev can change from 1 days to 30 days, initial is 30 days */ function changeLockPeriod(uint256 periodInDays) external onlyOwner { require(periodInDays <= 30 && periodInDays >= 1); lockPeriod = periodInDays * 1 days; } /** * @notice add a new token into the token list, only admins * @dev index 0 & 1 are saved for Ether and JOY * @dev both index & token can not be redundant, and no removed mathod * @param tokenAddress token's address * @param index chosen index of the token */ function registerToken(address tokenAddress, uint256 index) external onlyAdmin { require(index > 1); require(tokenAddress2Id[tokenAddress] == 0); require(tokenId2Address[index] == 0); tokenAddress2Id[tokenAddress] = index; tokenId2Address[index] = tokenAddress; } /** * @notice withdraw with admins involved, only admin * @param inputs array of inputs, must have 5 elements * @dev inputs encoding please reference github wiki */ function withdrawByAdmin_Unau(uint256[] inputs) external onlyAdmin { uint256 amount = inputs[0]; uint256 gasFee = inputs[1]; uint256 data = inputs[2]; uint256 paymentMethod = data & PAYMENT_METHOD_MASK; address token = tokenId2Address[(data & WITHDRAW_TOKEN_MASK) >> 32]; address user = userId2Address[data & USER_MASK]; bytes32 hash = keccak256( this, amount, gasFee, data & SIGN_MASK | uint256(token) ); require(!usedHash[hash]); require( verify( hash, user, uint8(data & V_MASK == 0 ? 27 : 28), bytes32(inputs[3]), bytes32(inputs[4]) ) ); address gasToken = 0; if (paymentMethod == PAY_BY_JOY) { // pay fee by JOY gasToken = joyToken; } else if (paymentMethod == PAY_BY_TOKEN) { // pay fee by tx token gasToken = token; } if (gasToken == token) { // pay by ether or token balances[token][user] = balances[token][user].sub(amount.add(gasFee)); } else { balances[token][user] = balances[token][user].sub(amount); balances[gasToken][user] = balances[gasToken][user].sub(gasFee); } balances[gasToken][joysoWallet] = balances[gasToken][joysoWallet].add(gasFee); usedHash[hash] = true; if (token == 0) { user.transfer(amount); } else { require(ERC20(token).transfer(user, amount)); } } /** * @notice match orders with admins involved, only admin * @param inputs Array of input orders, each order have 6 elements. Inputs must conatin at least 2 orders. * @dev inputs encoding please reference github wiki */ function matchByAdmin_TwH36(uint256[] inputs) external onlyAdmin { uint256 data = inputs[3]; address user = userId2Address[data & USER_MASK]; // check taker order nonce require(data >> 224 > userNonce[user]); address token; bool isBuy; (token, isBuy) = decodeOrderTokenAndIsBuy(data); bytes32 orderHash = keccak256( this, inputs[0], inputs[1], inputs[2], data & MATCH_SIGN_MASK | (isBuy ? ORDER_ISBUY : 0) | uint256(token) ); require( verify( orderHash, user, uint8(data & V_MASK == 0 ? 27 : 28), bytes32(inputs[4]), bytes32(inputs[5]) ) ); uint256 tokenExecute = isBuy ? inputs[1] : inputs[0]; // taker order token execute tokenExecute = tokenExecute.sub(orderFills[orderHash]); require(tokenExecute != 0); // the taker order should remain something to trade uint256 etherExecute = 0; // taker order ether execute isBuy = !isBuy; for (uint256 i = 6; i < inputs.length; i += 6) { //check price, maker price should lower than taker price require(tokenExecute > 0 && inputs[1].mul(inputs[i + 1]) <= inputs[0].mul(inputs[i])); data = inputs[i + 3]; user = userId2Address[data & USER_MASK]; // check maker order nonce require(data >> 224 > userNonce[user]); bytes32 makerOrderHash = keccak256( this, inputs[i], inputs[i + 1], inputs[i + 2], data & MATCH_SIGN_MASK | (isBuy ? ORDER_ISBUY : 0) | uint256(token) ); require( verify( makerOrderHash, user, uint8(data & V_MASK == 0 ? 27 : 28), bytes32(inputs[i + 4]), bytes32(inputs[i + 5]) ) ); (tokenExecute, etherExecute) = internalTrade( inputs[i], inputs[i + 1], inputs[i + 2], data, tokenExecute, etherExecute, isBuy, token, 0, makerOrderHash ); } isBuy = !isBuy; tokenExecute = isBuy ? inputs[1].sub(tokenExecute) : inputs[0].sub(tokenExecute); tokenExecute = tokenExecute.sub(orderFills[orderHash]); processTakerOrder(inputs[2], inputs[3], tokenExecute, etherExecute, isBuy, token, 0, orderHash); } /** * @notice match token orders with admins involved, only admin * @param inputs Array of input orders, each order have 6 elements. Inputs must conatin at least 2 orders. * @dev inputs encoding please reference github wiki */ function matchTokenOrderByAdmin_k44j(uint256[] inputs) external onlyAdmin { address user = userId2Address[decodeOrderUserId(inputs[3])]; // check taker order nonce require(inputs[3] >> 224 > userNonce[user]); address token; address base; bool isBuy; (token, base, isBuy) = decodeTokenOrderTokenAndIsBuy(inputs[3]); bytes32 orderHash = getTokenOrderDataHash(inputs, 0, inputs[3], token, base); require( verify( orderHash, user, uint8(retrieveV(inputs[3])), bytes32(inputs[4]), bytes32(inputs[5]) ) ); uint256 tokenExecute = isBuy ? inputs[1] : inputs[0]; // taker order token execute tokenExecute = tokenExecute.sub(orderFills[orderHash]); require(tokenExecute != 0); // the taker order should remain something to trade uint256 baseExecute = 0; // taker order ether execute isBuy = !isBuy; for (uint256 i = 6; i < inputs.length; i += 6) { //check price, taker price should better than maker price require(tokenExecute > 0 && inputs[1].mul(inputs[i + 1]) <= inputs[0].mul(inputs[i])); user = userId2Address[decodeOrderUserId(inputs[i + 3])]; // check maker order nonce require(inputs[i + 3] >> 224 > userNonce[user]); bytes32 makerOrderHash = getTokenOrderDataHash(inputs, i, inputs[i + 3], token, base); require( verify( makerOrderHash, user, uint8(retrieveV(inputs[i + 3])), bytes32(inputs[i + 4]), bytes32(inputs[i + 5]) ) ); (tokenExecute, baseExecute) = internalTrade( inputs[i], inputs[i + 1], inputs[i + 2], inputs[i + 3], tokenExecute, baseExecute, isBuy, token, base, makerOrderHash ); } isBuy = !isBuy; tokenExecute = isBuy ? inputs[1].sub(tokenExecute) : inputs[0].sub(tokenExecute); tokenExecute = tokenExecute.sub(orderFills[orderHash]); processTakerOrder(inputs[2], inputs[3], tokenExecute, baseExecute, isBuy, token, base, orderHash); } /** * @notice update user on-chain nonce with admins involved, only admin * @param inputs Array of input data, must have 4 elements. * @dev inputs encoding please reference github wiki */ function cancelByAdmin(uint256[] inputs) external onlyAdmin { uint256 data = inputs[1]; uint256 nonce = data >> 224; address user = userId2Address[data & USER_MASK]; require(nonce > userNonce[user]); uint256 gasFee = inputs[0]; require( verify( keccak256(this, gasFee, data & SIGN_MASK), user, uint8(retrieveV(data)), bytes32(inputs[2]), bytes32(inputs[3]) ) ); // update balance address gasToken = 0; if (data & PAYMENT_METHOD_MASK == PAY_BY_JOY) { gasToken = joyToken; } require(balances[gasToken][user] >= gasFee); balances[gasToken][user] = balances[gasToken][user].sub(gasFee); balances[gasToken][joysoWallet] = balances[gasToken][joysoWallet].add(gasFee); // update user nonce userNonce[user] = nonce; } /** * @notice batch send the current balance to the new version contract * @param inputs Array of input data * @dev inputs encoding please reference github wiki */ function migrateByAdmin_DQV(uint256[] inputs) external onlyAdmin { uint256 data = inputs[2]; address token = tokenId2Address[(data & WITHDRAW_TOKEN_MASK) >> 32]; address newContract = address(inputs[0]); for (uint256 i = 1; i < inputs.length; i += 4) { uint256 gasFee = inputs[i]; data = inputs[i + 1]; address user = userId2Address[data & USER_MASK]; bytes32 hash = keccak256( this, gasFee, data & SIGN_MASK | uint256(token), newContract ); require( verify( hash, user, uint8(data & V_MASK == 0 ? 27 : 28), bytes32(inputs[i + 2]), bytes32(inputs[i + 3]) ) ); if (gasFee > 0) { uint256 paymentMethod = data & PAYMENT_METHOD_MASK; if (paymentMethod == PAY_BY_JOY) { balances[joyToken][user] = balances[joyToken][user].sub(gasFee); balances[joyToken][joysoWallet] = balances[joyToken][joysoWallet].add(gasFee); } else if (paymentMethod == PAY_BY_TOKEN) { balances[token][user] = balances[token][user].sub(gasFee); balances[token][joysoWallet] = balances[token][joysoWallet].add(gasFee); } else { balances[0][user] = balances[0][user].sub(gasFee); balances[0][joysoWallet] = balances[0][joysoWallet].add(gasFee); } } uint256 amount = balances[token][user]; balances[token][user] = 0; if (token == 0) { Migratable(newContract).migrate.value(amount)(user, amount, token); } else { ERC20(token).approve(newContract, amount); Migratable(newContract).migrate(user, amount, token); } } } /** * @notice transfer token from admin to users * @param token address of token * @param account receiver's address * @param amount amount to transfer */ function transferForAdmin(address token, address account, uint256 amount) onlyAdmin external { require(tokenAddress2Id[token] != 0); require(userAddress2Id[msg.sender] != 0); addUser(account); balances[token][msg.sender] = balances[token][msg.sender].sub(amount); balances[token][account] = balances[token][account].add(amount); } /** * @notice get balance information * @param token address of token * @param account address of user */ function getBalance(address token, address account) external view returns (uint256) { return balances[token][account]; } /** * @dev get tokenId and check the order is a buy order or not, internal * tokenId take 4 bytes * isBuy is true means this order is buying token */ function decodeOrderTokenAndIsBuy(uint256 data) internal view returns (address token, bool isBuy) { uint256 tokenId = (data & TOKEN_SELL_MASK) >> 48; if (tokenId == 0) { token = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32]; isBuy = true; } else { token = tokenId2Address[tokenId]; } } /** * @dev decode token oreder data, internal */ function decodeTokenOrderTokenAndIsBuy(uint256 data) internal view returns (address token, address base, bool isBuy) { isBuy = data & IS_BUY_MASK == ORDER_ISBUY; if (isBuy) { token = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32]; base = tokenId2Address[(data & TOKEN_SELL_MASK) >> 48]; } else { token = tokenId2Address[(data & TOKEN_SELL_MASK) >> 48]; base = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32]; } } function getTime() internal view returns (uint256) { return now; } /** * @dev get token order's hash for user to sign, internal * @param inputs forword tokenOrderMatch's input to this function * @param offset offset of the order in inputs */ function getTokenOrderDataHash(uint256[] inputs, uint256 offset, uint256 data, address token, address base) internal view returns (bytes32) { return keccak256( this, inputs[offset], inputs[offset + 1], inputs[offset + 2], data & SIGN_MASK | uint256(token), base, (data & TOKEN_JOY_PRICE_MASK) >> 64 ); } /** * @dev check if the provided signature is valid, internal * @param hash signed information * @param sender signer address * @param v sig_v * @param r sig_r * @param s sig_s */ function verify(bytes32 hash, address sender, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { return ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == sender; } /** * @dev give a new user an id, intrnal */ function addUser(address _address) internal { if (userAddress2Id[_address] != 0) { return; } userCount += 1; userAddress2Id[_address] = userCount; userId2Address[userCount] = _address; NewUser(_address, userCount); } function processTakerOrder( uint256 gasFee, uint256 data, uint256 tokenExecute, uint256 baseExecute, bool isBuy, address token, address base, bytes32 orderHash ) internal { uint256 fee = calculateFee(gasFee, data, baseExecute, orderHash, true, base == 0); updateUserBalance(data, isBuy, baseExecute, tokenExecute, fee, token, base); orderFills[orderHash] = orderFills[orderHash].add(tokenExecute); if (tradeEventEnabled) { TradeSuccess(userId2Address[data & USER_MASK], baseExecute, tokenExecute, isBuy, fee); } } function internalTrade( uint256 amountSell, uint256 amountBuy, uint256 gasFee, uint256 data, uint256 _remainingToken, uint256 _baseExecute, bool isBuy, address token, address base, bytes32 orderHash ) internal returns (uint256 remainingToken, uint256 baseExecute) { uint256 tokenGet = calculateTokenGet(amountSell, amountBuy, _remainingToken, isBuy, orderHash); uint256 baseGet = calculateBaseGet(amountSell, amountBuy, isBuy, tokenGet); uint256 fee = calculateFee(gasFee, data, baseGet, orderHash, false, base == 0); updateUserBalance(data, isBuy, baseGet, tokenGet, fee, token, base); orderFills[orderHash] = orderFills[orderHash].add(tokenGet); remainingToken = _remainingToken.sub(tokenGet); baseExecute = _baseExecute.add(baseGet); if (tradeEventEnabled) { TradeSuccess( userId2Address[data & USER_MASK], baseGet, tokenGet, isBuy, fee ); } } function updateUserBalance( uint256 data, bool isBuy, uint256 baseGet, uint256 tokenGet, uint256 fee, address token, address base ) internal { address user = userId2Address[data & USER_MASK]; uint256 baseFee = fee; uint256 joyFee = 0; if ((base == 0 ? (data & JOY_PRICE_MASK) >> 164 : (data & TOKEN_JOY_PRICE_MASK) >> 64) != 0) { joyFee = fee; baseFee = 0; } if (isBuy) { // buy token, sell ether balances[base][user] = balances[base][user].sub(baseGet).sub(baseFee); balances[token][user] = balances[token][user].add(tokenGet); } else { balances[base][user] = balances[base][user].add(baseGet).sub(baseFee); balances[token][user] = balances[token][user].sub(tokenGet); } if (joyFee != 0) { balances[joyToken][user] = balances[joyToken][user].sub(joyFee); balances[joyToken][joysoWallet] = balances[joyToken][joysoWallet].add(joyFee); } else { balances[base][joysoWallet] = balances[base][joysoWallet].add(baseFee); } } function calculateFee( uint256 gasFee, uint256 data, uint256 baseGet, bytes32 orderHash, bool isTaker, bool isEthOrder ) internal view returns (uint256) { uint256 fee = orderFills[orderHash] == 0 ? gasFee : 0; uint256 txFee = baseGet.mul(isTaker ? (data & TAKER_FEE_MASK) >> 208 : (data & MAKER_FEE_MASK) >> 192) / 10000; uint256 joyPrice = isEthOrder ? (data & JOY_PRICE_MASK) >> 164 : (data & TOKEN_JOY_PRICE_MASK) >> 64; if (joyPrice != 0) { txFee = isEthOrder ? txFee / (10 ** 5) / joyPrice : txFee * (10 ** 12) / joyPrice; } return fee.add(txFee); } function calculateBaseGet( uint256 amountSell, uint256 amountBuy, bool isBuy, uint256 tokenGet ) internal pure returns (uint256) { return isBuy ? tokenGet.mul(amountSell) / amountBuy : tokenGet.mul(amountBuy) / amountSell; } function calculateTokenGet( uint256 amountSell, uint256 amountBuy, uint256 remainingToken, bool isBuy, bytes32 orderHash ) internal view returns (uint256) { uint256 makerRemainingToken = isBuy ? amountBuy : amountSell; makerRemainingToken = makerRemainingToken.sub(orderFills[orderHash]); require(makerRemainingToken > 0); // the maker order should remain something to trade return makerRemainingToken >= remainingToken ? remainingToken : makerRemainingToken; } }
match token orders with admins involved, only admin inputs Array of input orders, each order have 6 elements. Inputs must conatin at least 2 orders. inputs encoding please reference github wiki/ check taker order nonce
function matchTokenOrderByAdmin_k44j(uint256[] inputs) external onlyAdmin { address user = userId2Address[decodeOrderUserId(inputs[3])]; require(inputs[3] >> 224 > userNonce[user]); address token; address base; bool isBuy; (token, base, isBuy) = decodeTokenOrderTokenAndIsBuy(inputs[3]); bytes32 orderHash = getTokenOrderDataHash(inputs, 0, inputs[3], token, base); require( verify( orderHash, user, uint8(retrieveV(inputs[3])), bytes32(inputs[4]), bytes32(inputs[5]) ) ); tokenExecute = tokenExecute.sub(orderFills[orderHash]); isBuy = !isBuy; for (uint256 i = 6; i < inputs.length; i += 6) { require(tokenExecute > 0 && inputs[1].mul(inputs[i + 1]) <= inputs[0].mul(inputs[i])); user = userId2Address[decodeOrderUserId(inputs[i + 3])]; require(inputs[i + 3] >> 224 > userNonce[user]); bytes32 makerOrderHash = getTokenOrderDataHash(inputs, i, inputs[i + 3], token, base); require( verify( makerOrderHash, user, uint8(retrieveV(inputs[i + 3])), bytes32(inputs[i + 4]), bytes32(inputs[i + 5]) ) ); (tokenExecute, baseExecute) = internalTrade( inputs[i], inputs[i + 1], inputs[i + 2], inputs[i + 3], tokenExecute, baseExecute, isBuy, token, base, makerOrderHash ); } isBuy = !isBuy; tokenExecute = isBuy ? inputs[1].sub(tokenExecute) : inputs[0].sub(tokenExecute); tokenExecute = tokenExecute.sub(orderFills[orderHash]); processTakerOrder(inputs[2], inputs[3], tokenExecute, baseExecute, isBuy, token, base, orderHash); }
900,945
pragma solidity ^0.5.3; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/IReserve.sol"; import "./interfaces/ISortedOracles.sol"; import "./interfaces/IStableToken.sol"; import "../common/FixidityLib.sol"; import "../common/Initializable.sol"; import "../common/UsingRegistry.sol"; /** * @title Ensures price stability of StableTokens with respect to their pegs */ contract Reserve is IReserve, Ownable, Initializable, UsingRegistry, ReentrancyGuard { using SafeMath for uint256; using FixidityLib for FixidityLib.Fraction; struct TobinTaxCache { uint128 numerator; uint128 timestamp; } mapping(address => bool) public isToken; address[] private _tokens; TobinTaxCache public tobinTaxCache; uint256 public tobinTaxStalenessThreshold; uint256 public constant TOBIN_TAX_NUMERATOR = 5000000000000000000000; // 0.005 mapping(address => bool) public isSpender; mapping(address => bool) public isOtherReserveAddress; address[] public otherReserveAddresses; bytes32[] public assetAllocationSymbols; uint256[] public assetAllocationWeights; uint256 public lastSpendingDay; uint256 public spendingLimit; FixidityLib.Fraction private spendingRatio; event TobinTaxStalenessThresholdSet(uint256 value); event DailySpendingRatioSet(uint256 ratio); event TokenAdded(address token); event TokenRemoved(address token, uint256 index); event SpenderAdded(address spender); event SpenderRemoved(address spender); event OtherReserveAddressAdded(address otherReserveAddress); event OtherReserveAddressRemoved(address otherReserveAddress, uint256 index); event AssetAllocationSet(bytes32[] symbols, uint256[] weights); modifier isStableToken(address token) { require(isToken[token], "token addr was never registered"); _; } function() external payable {} // solhint-disable no-empty-blocks /** * @notice Initializes critical variables. * @param registryAddress The address of the registry contract. * @param _tobinTaxStalenessThreshold The initial number of seconds to cache tobin tax value for. */ function initialize( address registryAddress, uint256 _tobinTaxStalenessThreshold, uint256 _spendingRatio ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setTobinTaxStalenessThreshold(_tobinTaxStalenessThreshold); setDailySpendingRatio(_spendingRatio); } /** * @notice Sets the number of seconds to cache the tobin tax value for. * @param value The number of seconds to cache the tobin tax value for. */ function setTobinTaxStalenessThreshold(uint256 value) public onlyOwner { require(value > 0, "value was zero"); tobinTaxStalenessThreshold = value; emit TobinTaxStalenessThresholdSet(value); } /** * @notice Set the ratio of reserve that is spendable per day. * @param ratio Spending ratio as unwrapped Fraction. */ function setDailySpendingRatio(uint256 ratio) public onlyOwner { spendingRatio = FixidityLib.wrap(ratio); require(spendingRatio.lte(FixidityLib.fixed1()), "spending ratio cannot be larger than 1"); emit DailySpendingRatioSet(ratio); } /** * @notice Get daily spending ratio. * @return Spending ratio as unwrapped Fraction. */ function getDailySpendingRatio() public view onlyOwner returns (uint256) { return spendingRatio.unwrap(); } /** * @notice Sets target allocations for Celo Gold and a diversified basket of non-Celo assets. * @param symbols The symbol of each asset in the Reserve portfolio. * @param weights The weight for the corresponding asset as unwrapped Fixidity.Fraction. */ function setAssetAllocations(bytes32[] calldata symbols, uint256[] calldata weights) external onlyOwner { require(symbols.length == weights.length, "Array length mismatch"); FixidityLib.Fraction memory sum = FixidityLib.wrap(0); for (uint256 i = 0; i < weights.length; i++) { sum = sum.add(FixidityLib.wrap(weights[i])); } require(sum.equals(FixidityLib.fixed1()), "Sum of asset allocation must be 1"); assetAllocationSymbols = symbols; assetAllocationWeights = weights; emit AssetAllocationSet(symbols, weights); } /** * @notice Add a token that the reserve will stablize. * @param token The address of the token being stabilized. */ function addToken(address token) external onlyOwner nonReentrant returns (bool) { require(!isToken[token], "token addr already registered"); // Require an exchange rate between the new token and Gold exists. address sortedOraclesAddress = registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID); ISortedOracles sortedOracles = ISortedOracles(sortedOraclesAddress); uint256 tokenAmount; uint256 goldAmount; (tokenAmount, goldAmount) = sortedOracles.medianRate(token); require(goldAmount > 0, "median rate returned 0 gold"); isToken[token] = true; _tokens.push(token); emit TokenAdded(token); return true; } /** * @notice Remove a token that the reserve will no longer stabilize. * @param token The address of the token no longer being stabilized. * @param index The index of the token in _tokens. */ function removeToken(address token, uint256 index) external onlyOwner isStableToken(token) returns (bool) { require( index < _tokens.length && _tokens[index] == token, "index into tokens list not mapped to token" ); isToken[token] = false; address lastItem = _tokens[_tokens.length - 1]; _tokens[index] = lastItem; _tokens.length--; emit TokenRemoved(token, index); return true; } /** * @notice Add a reserve address whose balance shall be included in the reserve ratio. * @param reserveAddress The reserve address to add. */ function addOtherReserveAddress(address reserveAddress) external onlyOwner nonReentrant returns (bool) { require(!isOtherReserveAddress[reserveAddress], "reserve addr already added"); isOtherReserveAddress[reserveAddress] = true; otherReserveAddresses.push(reserveAddress); emit OtherReserveAddressAdded(reserveAddress); return true; } /** * @notice Remove reserve address whose balance shall no longer be included in the reserve ratio. * @param reserveAddress The reserve address to remove. * @param index The index of the reserve address in otherReserveAddresses. */ function removeOtherReserveAddress(address reserveAddress, uint256 index) external onlyOwner returns (bool) { require(isOtherReserveAddress[reserveAddress], "reserve addr was never added"); require( index < otherReserveAddresses.length && otherReserveAddresses[index] == reserveAddress, "index into reserve list not mapped to address" ); isOtherReserveAddress[reserveAddress] = false; address lastItem = otherReserveAddresses[otherReserveAddresses.length - 1]; otherReserveAddresses[index] = lastItem; otherReserveAddresses.length--; emit OtherReserveAddressRemoved(reserveAddress, index); return true; } /** * @notice Gives an address permission to spend Reserve funds. * @param spender The address that is allowed to spend Reserve funds. */ function addSpender(address spender) external onlyOwner { isSpender[spender] = true; emit SpenderAdded(spender); } /** * @notice Takes away an address's permission to spend Reserve funds. * @param spender The address that is to be no longer allowed to spend Reserve funds. */ function removeSpender(address spender) external onlyOwner { isSpender[spender] = false; emit SpenderRemoved(spender); } /** * @notice Transfer gold. * @param to The address that will receive the gold. * @param value The amount of gold to transfer. */ function transferGold(address to, uint256 value) external returns (bool) { require(isSpender[msg.sender], "sender not allowed to transfer Reserve funds"); uint256 currentDay = now / 1 days; if (currentDay > lastSpendingDay) { uint256 balance = getReserveGoldBalance(); lastSpendingDay = currentDay; spendingLimit = spendingRatio.multiply(FixidityLib.newFixed(balance)).fromFixed(); } require(spendingLimit >= value, "Exceeding spending limit"); spendingLimit = spendingLimit.sub(value); require(getGoldToken().transfer(to, value), "transfer of gold token failed"); return true; } /** * @notice Returns the tobin tax, recomputing it if it's stale. * @return The tobin tax amount as a fraction. */ function getOrComputeTobinTax() external nonReentrant returns (uint256, uint256) { // solhint-disable-next-line not-rely-on-time if (now.sub(tobinTaxCache.timestamp) > tobinTaxStalenessThreshold) { tobinTaxCache.numerator = uint128(computeTobinTax().unwrap()); tobinTaxCache.timestamp = uint128(now); // solhint-disable-line not-rely-on-time } return (uint256(tobinTaxCache.numerator), FixidityLib.fixed1().unwrap()); } function getTokens() external view returns (address[] memory) { return _tokens; } function getOtherReserveAddresses() external view returns (address[] memory) { return otherReserveAddresses; } function getAssetAllocationSymbols() external view returns (bytes32[] memory) { return assetAllocationSymbols; } function getAssetAllocationWeights() external view returns (uint256[] memory) { return assetAllocationWeights; } function getReserveGoldBalance() public view returns (uint256) { uint256 reserveGoldBalance = address(this).balance; for (uint256 i = 0; i < otherReserveAddresses.length; i++) { reserveGoldBalance = reserveGoldBalance.add(otherReserveAddresses[i].balance); } return reserveGoldBalance; } /* * Internal functions */ /** * @notice Computes a tobin tax based on the reserve ratio. * @return The numerator of the tobin tax amount, where the denominator is 1000. */ function computeTobinTax() private view returns (FixidityLib.Fraction memory) { address sortedOraclesAddress = registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID); ISortedOracles sortedOracles = ISortedOracles(sortedOraclesAddress); uint256 reserveGoldBalance = getReserveGoldBalance(); uint256 stableTokensValueInGold = 0; for (uint256 i = 0; i < _tokens.length; i++) { uint256 stableAmount; uint256 goldAmount; (stableAmount, goldAmount) = sortedOracles.medianRate(_tokens[i]); uint256 stableTokenSupply = IERC20Token(_tokens[i]).totalSupply(); uint256 aStableTokenValueInGold = stableTokenSupply.mul(goldAmount).div(stableAmount); stableTokensValueInGold = stableTokensValueInGold.add(aStableTokenValueInGold); } // The protocol calls for a 0.5% transfer tax on Celo Gold when the reserve ratio < 2. // The protocol aims to keep half of the reserve value in gold, thus the reserve ratio // is two when the value of gold in the reserve is equal to the total supply of stable tokens. if (reserveGoldBalance >= stableTokensValueInGold) { return FixidityLib.wrap(0); } else { return FixidityLib.wrap(TOBIN_TAX_NUMERATOR); } } /** * @notice Mint tokens. * @param to The address that will receive the minted tokens. * @param token The address of the token to mint. * @param value The amount of tokens to mint. */ function mintToken(address to, address token, uint256 value) private isStableToken(token) returns (bool) { IStableToken stableToken = IStableToken(token); stableToken.mint(to, value); return true; } }
Mint tokens. to The address that will receive the minted tokens. token The address of the token to mint. value The amount of tokens to mint./
function mintToken(address to, address token, uint256 value) private isStableToken(token) returns (bool) { IStableToken stableToken = IStableToken(token); stableToken.mint(to, value); return true; }
14,112,034
./partial_match/56/0x72FEAC4C0887c12db21CEB161533Fd8467469e6b/sources/DeadSoulToken.sol
View function to see pending CAKEs on frontend. If Pool 1 then use totalAmount instead of actual balance - due to SOUL burn balance is 0
function pendingCake(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCakePerShare = pool.accCakePerShare; uint256 lpSupply = 0; else { lpSupply = pool.lpToken.balanceOf(address(this)); } if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(cakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCakePerShare = accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCakePerShare).div(1e12).sub(user.rewardDebt); }
11,070,424
./full_match/1/0xB6eB928D47f4562A8e704acbdA3F52423fEbbF0d/sources/contracts/CoolERC721A.sol
Set the max limit of tokens that can be minted Can only be called by a manager maxLimit The new max limit
function setMaxLimit(uint256 maxLimit) public onlyManager { MAX_LIMIT = maxLimit; emit MaxLimitChanged(maxLimit); }
9,703,913
./full_match/1/0xfbB3742628e8D19E0E2d7D8dde208821C09dE960/sources/src/policies/BoostedLiquidity/interfaces/IAura.sol
Define Base Reward Pool interface
interface IAuraRewardPool { function balanceOf(address account_) external view returns (uint256); function earned(address account_) external view returns (uint256); function rewardRate() external view returns (uint256); function rewardToken() external view returns (address); function extraRewardsLength() external view returns (uint256); function extraRewards(uint256 index) external view returns (address); function deposit(uint256 assets_, address receiver_) external; function getReward(address account_, bool claimExtras_) external; function withdrawAndUnwrap(uint256 amount_, bool claim_) external returns (bool); }
4,916,300
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../ConverterVersion.sol"; import "../../interfaces/IConverter.sol"; import "../../interfaces/IConverterAnchor.sol"; import "../../interfaces/IConverterUpgrader.sol"; import "../../../utility/MathEx.sol"; import "../../../utility/ContractRegistryClient.sol"; import "../../../utility/Time.sol"; import "../../../token/interfaces/IDSToken.sol"; import "../../../token/ReserveToken.sol"; import "../../../INetworkSettings.sol"; /** * @dev This contract is a specialized version of the converter, which is * optimized for a liquidity pool that has 2 reserves with 50%/50% weights. */ contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time { using SafeMath for uint256; using ReserveToken for IReserveToken; using SafeERC20 for IERC20; using MathEx for *; uint256 private constant MAX_UINT128 = 2**128 - 1; uint256 private constant MAX_UINT112 = 2**112 - 1; uint256 private constant MAX_UINT32 = 2**32 - 1; uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes; uint256 private _reserveBalances; uint256 private _reserveBalancesProduct; IReserveToken[] private _reserveTokens; mapping(IReserveToken => uint256) private _reserveIds; IConverterAnchor private _anchor; // converter anchor contract uint32 private _maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000 uint32 private _conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee // average rate details: // bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1 // bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1 // bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1 // where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1 uint256 private _averageRateInfo; /** * @dev triggered after liquidity is added * * @param provider liquidity provider * @param reserveToken reserve token address * @param amount reserve token amount * @param newBalance reserve token new balance * @param newSupply pool token new supply */ event LiquidityAdded( address indexed provider, IReserveToken indexed reserveToken, uint256 amount, uint256 newBalance, uint256 newSupply ); /** * @dev triggered after liquidity is removed * * @param provider liquidity provider * @param reserveToken reserve token address * @param amount reserve token amount * @param newBalance reserve token new balance * @param newSupply pool token new supply */ event LiquidityRemoved( address indexed provider, IReserveToken indexed reserveToken, uint256 amount, uint256 newBalance, uint256 newSupply ); /** * @dev initializes a new StandardPoolConverter instance * * @param anchor anchor governed by the converter * @param registry address of a contract registry contract * @param maxConversionFee maximum conversion fee, represented in ppm */ constructor( IConverterAnchor anchor, IContractRegistry registry, uint32 maxConversionFee ) public ContractRegistryClient(registry) validAddress(address(anchor)) validConversionFee(maxConversionFee) { _anchor = anchor; _maxConversionFee = maxConversionFee; } // ensures that the converter is active modifier active() { _active(); _; } // error message binary size optimization function _active() private view { require(isActive(), "ERR_INACTIVE"); } // ensures that the converter is not active modifier inactive() { _inactive(); _; } // error message binary size optimization function _inactive() private view { require(!isActive(), "ERR_ACTIVE"); } // validates a reserve token address - verifies that the address belongs to one of the reserve tokens modifier validReserve(IReserveToken reserveToken) { _validReserve(reserveToken); _; } // error message binary size optimization function _validReserve(IReserveToken reserveToken) private view { require(_reserveIds[reserveToken] != 0, "ERR_INVALID_RESERVE"); } // validates conversion fee modifier validConversionFee(uint32 fee) { _validConversionFee(fee); _; } // error message binary size optimization function _validConversionFee(uint32 fee) private pure { require(fee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE"); } // validates reserve weight modifier validReserveWeight(uint32 weight) { _validReserveWeight(weight); _; } // error message binary size optimization function _validReserveWeight(uint32 weight) private pure { require(weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT"); } /** * @dev returns the converter type * * @return see the converter types in the the main contract doc */ function converterType() public pure virtual override returns (uint16) { return 3; } /** * @dev checks whether or not the converter version is 28 or higher * * @return true, since the converter version is 28 or higher */ function isV28OrHigher() external pure returns (bool) { return true; } /** * @dev returns the converter anchor * * @return the converter anchor */ function anchor() external view override returns (IConverterAnchor) { return _anchor; } /** * @dev returns the maximum conversion fee (in units of PPM) * * @return the maximum conversion fee (in units of PPM) */ function maxConversionFee() external view override returns (uint32) { return _maxConversionFee; } /** * @dev returns the current conversion fee (in units of PPM) * * @return the current conversion fee (in units of PPM) */ function conversionFee() external view override returns (uint32) { return _conversionFee; } /** * @dev returns the average rate info * * @return the average rate info */ function averageRateInfo() external view returns (uint256) { return _averageRateInfo; } /** * @dev deposits ether * can only be called if the converter has an ETH reserve */ receive() external payable override(IConverter) validReserve(ReserveToken.NATIVE_TOKEN_ADDRESS) {} /** * @dev returns true if the converter is active, false otherwise * * @return true if the converter is active, false otherwise */ function isActive() public view virtual override returns (bool) { return _anchor.owner() == address(this); } /** * @dev transfers the anchor ownership * the new owner needs to accept the transfer * can only be called by the converter upgrader while the upgrader is the owner * note that prior to version 28, you should use 'transferAnchorOwnership' instead * * @param newOwner new token owner */ function transferAnchorOwnership(address newOwner) public override ownerOnly only(CONVERTER_UPGRADER) { _anchor.transferOwnership(newOwner); } /** * @dev accepts ownership of the anchor after an ownership transfer * most converters are also activated as soon as they accept the anchor ownership * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public virtual override ownerOnly { // verify the the converter has exactly two reserves require(_reserveTokens.length == 2, "ERR_INVALID_RESERVE_COUNT"); _anchor.acceptOwnership(); syncReserveBalances(0); emit Activation(converterType(), _anchor, true); } /** * @dev updates the current conversion fee * can only be called by the contract owner * * @param fee new conversion fee, represented in ppm */ function setConversionFee(uint32 fee) external override ownerOnly { require(fee <= _maxConversionFee, "ERR_INVALID_CONVERSION_FEE"); emit ConversionFeeUpdate(_conversionFee, fee); _conversionFee = fee; } /** * @dev transfers reserve balances to a new converter during an upgrade * can only be called by the converter upgraded which should be set at its owner * * @param newConverter address of the converter to receive the new amount */ function transferReservesOnUpgrade(address newConverter) external override nonReentrant ownerOnly only(CONVERTER_UPGRADER) { uint256 reserveCount = _reserveTokens.length; for (uint256 i = 0; i < reserveCount; ++i) { IReserveToken reserveToken = _reserveTokens[i]; reserveToken.safeTransfer(newConverter, reserveToken.balanceOf(address(this))); syncReserveBalance(reserveToken); } } /** * @dev upgrades the converter to the latest version * can only be called by the owner * note that the owner needs to call acceptOwnership on the new converter after the upgrade */ function upgrade() external ownerOnly { IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER)); // trigger de-activation event emit Activation(converterType(), _anchor, false); transferOwnership(address(converterUpgrader)); converterUpgrader.upgrade(version); acceptOwnership(); } /** * @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic */ function onUpgradeComplete() external override nonReentrant ownerOnly only(CONVERTER_UPGRADER) { (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2); _reserveBalancesProduct = reserveBalance0 * reserveBalance1; } /** * @dev returns the number of reserve tokens * note that prior to version 17, you should use 'connectorTokenCount' instead * * @return number of reserve tokens */ function reserveTokenCount() public view override returns (uint16) { return uint16(_reserveTokens.length); } /** * @dev returns the array of reserve tokens * * @return array of reserve tokens */ function reserveTokens() external view override returns (IReserveToken[] memory) { return _reserveTokens; } /** * @dev defines a new reserve token for the converter * can only be called by the owner while the converter is inactive * * @param token address of the reserve token * @param weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IReserveToken token, uint32 weight) external virtual override ownerOnly inactive validExternalAddress(address(token)) validReserveWeight(weight) { require(address(token) != address(_anchor) && _reserveIds[token] == 0, "ERR_INVALID_RESERVE"); require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT"); _reserveTokens.push(token); _reserveIds[token] = _reserveTokens.length; } /** * @dev returns the reserve's weight * added in version 28 * * @param reserveToken reserve token contract address * * @return reserve weight */ function reserveWeight(IReserveToken reserveToken) external view validReserve(reserveToken) returns (uint32) { return PPM_RESOLUTION / 2; } /** * @dev returns the balance of a given reserve token * * @param reserveToken reserve token contract address * * @return the balance of the given reserve token */ function reserveBalance(IReserveToken reserveToken) public view override returns (uint256) { uint256 reserveId = _reserveIds[reserveToken]; require(reserveId != 0, "ERR_INVALID_RESERVE"); return reserveBalance(reserveId); } /** * @dev returns the balances of both reserve tokens * * @return the balances of both reserve tokens */ function reserveBalances() public view returns (uint256, uint256) { return reserveBalances(1, 2); } /** * @dev syncs all stored reserve balances */ function syncReserveBalances() external { syncReserveBalances(0); } /** * @dev calculates the accumulated network fee and transfers it to the network fee wallet */ function processNetworkFees() external nonReentrant { (uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0); _reserveBalancesProduct = reserveBalance0 * reserveBalance1; } /** * @dev calculates the accumulated network fee and transfers it to the network fee wallet * * @param value amount of ether to exclude from the ether reserve balance (if relevant) * * @return new reserve balances */ function processNetworkFees(uint256 value) private returns (uint256, uint256) { syncReserveBalances(value); (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2); (ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1); reserveBalance0 -= fee0; reserveBalance1 -= fee1; setReserveBalances(1, 2, reserveBalance0, reserveBalance1); _reserveTokens[0].safeTransfer(address(wallet), fee0); _reserveTokens[1].safeTransfer(address(wallet), fee1); return (reserveBalance0, reserveBalance1); } /** * @dev returns the reserve balances of the given reserve tokens minus their corresponding fees * * @param baseReserveTokens reserve tokens * * @return reserve balances minus their corresponding fees */ function baseReserveBalances(IReserveToken[] memory baseReserveTokens) private view returns (uint256[2] memory) { uint256 reserveId0 = _reserveIds[baseReserveTokens[0]]; uint256 reserveId1 = _reserveIds[baseReserveTokens[1]]; (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1); (, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1); return [reserveBalance0 - fee0, reserveBalance1 - fee1]; } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param sourceToken source reserve token * @param targetToken target reserve token * @param sourceAmount amount of tokens to convert (in units of the source token) * @param trader address of the caller who executed the conversion * @param beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function convert( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount, address trader, address payable beneficiary ) external payable override nonReentrant only(BANCOR_NETWORK) returns (uint256) { require(sourceToken != targetToken, "ERR_SAME_SOURCE_TARGET"); return doConvert(sourceToken, targetToken, sourceAmount, trader, beneficiary); } /** * @dev returns the conversion fee for a given target amount * * @param targetAmount target amount * * @return conversion fee */ function calculateFee(uint256 targetAmount) private view returns (uint256) { return targetAmount.mul(_conversionFee) / PPM_RESOLUTION; } /** * @dev returns the conversion fee taken from a given target amount * * @param targetAmount target amount * * @return conversion fee */ function calculateFeeInv(uint256 targetAmount) private view returns (uint256) { return targetAmount.mul(_conversionFee).div(PPM_RESOLUTION - _conversionFee); } /** * @dev loads the stored reserve balance for a given reserve id * * @param reserveId reserve id */ function reserveBalance(uint256 reserveId) private view returns (uint256) { return decodeReserveBalance(_reserveBalances, reserveId); } /** * @dev loads the stored reserve balances * * @param sourceId source reserve id * @param targetId target reserve id */ function reserveBalances(uint256 sourceId, uint256 targetId) private view returns (uint256, uint256) { require((sourceId == 1 && targetId == 2) || (sourceId == 2 && targetId == 1), "ERR_INVALID_RESERVES"); return decodeReserveBalances(_reserveBalances, sourceId, targetId); } /** * @dev stores the stored reserve balance for a given reserve id * * @param reserveId reserve id * @param balance reserve balance */ function setReserveBalance(uint256 reserveId, uint256 balance) private { require(balance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW"); uint256 otherBalance = decodeReserveBalance(_reserveBalances, 3 - reserveId); _reserveBalances = encodeReserveBalances(balance, reserveId, otherBalance, 3 - reserveId); } /** * @dev stores the stored reserve balances * * @param sourceId source reserve id * @param targetId target reserve id * @param sourceBalance source reserve balance * @param targetBalance target reserve balance */ function setReserveBalances( uint256 sourceId, uint256 targetId, uint256 sourceBalance, uint256 targetBalance ) private { require(sourceBalance <= MAX_UINT128 && targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW"); _reserveBalances = encodeReserveBalances(sourceBalance, sourceId, targetBalance, targetId); } /** * @dev syncs the stored reserve balance for a given reserve with the real reserve balance * * @param reserveToken address of the reserve token */ function syncReserveBalance(IReserveToken reserveToken) private { uint256 reserveId = _reserveIds[reserveToken]; setReserveBalance(reserveId, reserveToken.balanceOf(address(this))); } /** * @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant) * * @param value amount of ether to exclude from the ether reserve balance (if relevant) */ function syncReserveBalances(uint256 value) private { IReserveToken _reserveToken0 = _reserveTokens[0]; IReserveToken _reserveToken1 = _reserveTokens[1]; uint256 balance0 = _reserveToken0.balanceOf(address(this)) - (_reserveToken0.isNativeToken() ? value : 0); uint256 balance1 = _reserveToken1.balanceOf(address(this)) - (_reserveToken1.isNativeToken() ? value : 0); setReserveBalances(1, 2, balance0, balance1); } /** * @dev helper, dispatches the Conversion event * * @param sourceToken source ERC20 token * @param targetToken target ERC20 token * @param trader address of the caller who executed the conversion * @param sourceAmount amount purchased/sold (in the source token) * @param targetAmount amount returned (in the target token) * @param feeAmount the fee amount */ function dispatchConversionEvent( IReserveToken sourceToken, IReserveToken targetToken, address trader, uint256 sourceAmount, uint256 targetAmount, uint256 feeAmount ) private { emit Conversion(sourceToken, targetToken, trader, sourceAmount, targetAmount, int256(feeAmount)); } /** * @dev returns the expected amount and expected fee for converting one reserve to another * * @param sourceToken address of the source reserve token contract * @param targetToken address of the target reserve token contract * @param sourceAmount amount of source reserve tokens converted * * @return expected amount in units of the target reserve token * @return expected fee in units of the target reserve token */ function targetAmountAndFee( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount ) public view virtual override active returns (uint256, uint256) { uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); return targetAmountAndFee(sourceToken, targetToken, sourceBalance, targetBalance, sourceAmount); } /** * @dev returns the expected amount and expected fee for converting one reserve to another * * @param sourceBalance balance in the source reserve token contract * @param targetBalance balance in the target reserve token contract * @param sourceAmount amount of source reserve tokens converted * * @return expected amount in units of the target reserve token * @return expected fee in units of the target reserve token */ function targetAmountAndFee( IReserveToken, /* sourceToken */ IReserveToken, /* targetToken */ uint256 sourceBalance, uint256 targetBalance, uint256 sourceAmount ) private view returns (uint256, uint256) { uint256 targetAmount = crossReserveTargetAmount(sourceBalance, targetBalance, sourceAmount); uint256 fee = calculateFee(targetAmount); return (targetAmount - fee, fee); } /** * @dev returns the required amount and expected fee for converting one reserve to another * * @param sourceToken address of the source reserve token contract * @param targetToken address of the target reserve token contract * @param targetAmount amount of target reserve tokens desired * * @return required amount in units of the source reserve token * @return expected fee in units of the target reserve token */ function sourceAmountAndFee( IReserveToken sourceToken, IReserveToken targetToken, uint256 targetAmount ) public view virtual active returns (uint256, uint256) { uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); uint256 fee = calculateFeeInv(targetAmount); uint256 sourceAmount = crossReserveSourceAmount(sourceBalance, targetBalance, targetAmount.add(fee)); return (sourceAmount, fee); } /** * @dev converts a specific amount of source tokens to target tokens * * @param sourceToken source reserve token * @param targetToken target reserve token * @param sourceAmount amount of tokens to convert (in units of the source token) * @param trader address of the caller who executed the conversion * @param beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount, address trader, address payable beneficiary ) private returns (uint256) { // update the recent average rate updateRecentAverageRate(); uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); // get the target amount minus the conversion fee and the conversion fee (uint256 targetAmount, uint256 fee) = targetAmountAndFee(sourceToken, targetToken, sourceBalance, targetBalance, sourceAmount); // ensure that the trade gives something in return require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT"); // ensure that the trade won't deplete the reserve balance assert(targetAmount < targetBalance); // ensure that the input amount was already deposited uint256 actualSourceBalance = sourceToken.balanceOf(address(this)); if (sourceToken.isNativeToken()) { require(msg.value == sourceAmount, "ERR_ETH_AMOUNT_MISMATCH"); } else { require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= sourceAmount, "ERR_INVALID_AMOUNT"); } // sync the reserve balances setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - targetAmount); // transfer funds to the beneficiary in the to reserve token targetToken.safeTransfer(beneficiary, targetAmount); // dispatch the conversion event dispatchConversionEvent(sourceToken, targetToken, trader, sourceAmount, targetAmount, fee); // dispatch rate updates dispatchTokenRateUpdateEvents(sourceToken, targetToken, actualSourceBalance, targetBalance - targetAmount); return targetAmount; } /** * @dev returns the recent average rate of 1 token in the other reserve token units * * @param token token to get the rate for * * @return recent average rate between the reserves (numerator) * @return recent average rate between the reserves (denominator) */ function recentAverageRate(IReserveToken token) external view validReserve(token) returns (uint256, uint256) { // get the recent average rate of reserve 0 uint256 rate = calcRecentAverageRate(_averageRateInfo); uint256 rateN = decodeAverageRateN(rate); uint256 rateD = decodeAverageRateD(rate); if (token == _reserveTokens[0]) { return (rateN, rateD); } return (rateD, rateN); } /** * @dev updates the recent average rate if needed */ function updateRecentAverageRate() private { uint256 averageRateInfo1 = _averageRateInfo; uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1); if (averageRateInfo1 != averageRateInfo2) { _averageRateInfo = averageRateInfo2; } } /** * @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units * * @param averageRateInfoData the average rate to use for the calculation * * @return recent average rate between the reserves */ function calcRecentAverageRate(uint256 averageRateInfoData) private view returns (uint256) { // get the previous average rate and its update-time uint256 prevAverageRateT = decodeAverageRateT(averageRateInfoData); uint256 prevAverageRateN = decodeAverageRateN(averageRateInfoData); uint256 prevAverageRateD = decodeAverageRateD(averageRateInfoData); // get the elapsed time since the previous average rate was calculated uint256 currentTime = time(); uint256 timeElapsed = currentTime - prevAverageRateT; // if the previous average rate was calculated in the current block, the average rate remains unchanged if (timeElapsed == 0) { return averageRateInfoData; } // get the current rate between the reserves (uint256 currentRateD, uint256 currentRateN) = reserveBalances(); // if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) { (currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112); return encodeAverageRateInfo(currentTime, currentRateN, currentRateD); } uint256 x = prevAverageRateD.mul(currentRateN); uint256 y = prevAverageRateN.mul(currentRateD); // since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath: uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed)); uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD); (newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112); return encodeAverageRateInfo(currentTime, newRateN, newRateD); } /** * @dev increases the pool's liquidity and mints new shares in the pool to the caller * * @param reserves address of each reserve token * @param reserveAmounts amount of each reserve token * @param minReturn token minimum return-amount * * @return amount of pool tokens issued */ function addLiquidity( IReserveToken[] memory reserves, uint256[] memory reserveAmounts, uint256 minReturn ) external payable nonReentrant active returns (uint256) { // verify the user input verifyLiquidityInput(reserves, reserveAmounts, minReturn); // if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH require( (!reserves[0].isNativeToken() || reserveAmounts[0] == msg.value) && (!reserves[1].isNativeToken() || reserveAmounts[1] == msg.value), "ERR_ETH_AMOUNT_MISMATCH" ); // if the input value of ETH is larger than zero, then verify that one of the reserves is ETH if (msg.value > 0) { require(_reserveIds[ReserveToken.NATIVE_TOKEN_ADDRESS] != 0, "ERR_NO_ETH_RESERVE"); } // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply uint256 totalSupply = poolToken.totalSupply(); uint256[2] memory prevReserveBalances; uint256[2] memory newReserveBalances; // process the network fees and get the reserve balances (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value); uint256 amount; uint256[2] memory newReserveAmounts; // calculate the amount of pool tokens to mint for the caller // and the amount of reserve tokens to transfer from the caller if (totalSupply == 0) { amount = MathEx.geometricMean(reserveAmounts); newReserveAmounts[0] = reserveAmounts[0]; newReserveAmounts[1] = reserveAmounts[1]; } else { (amount, newReserveAmounts) = addLiquidityAmounts( reserves, reserveAmounts, prevReserveBalances, totalSupply ); } uint256 newPoolTokenSupply = totalSupply.add(amount); for (uint256 i = 0; i < 2; i++) { IReserveToken reserveToken = reserves[i]; uint256 reserveAmount = newReserveAmounts[i]; require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT"); assert(reserveAmount <= reserveAmounts[i]); // transfer each one of the reserve amounts from the user to the pool if (!reserveToken.isNativeToken()) { // ETH has already been transferred as part of the transaction reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount); } else if (reserveAmounts[i] > reserveAmount) { // transfer the extra amount of ETH back to the user reserveToken.safeTransfer(msg.sender, reserveAmounts[i] - reserveAmount); } // save the new reserve balance newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount); emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply); } // set the reserve balances setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]); // set the reserve balances product _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1]; // verify that the equivalent amount of tokens is equal to or larger than the user's expectation require(amount >= minReturn, "ERR_RETURN_TOO_LOW"); // issue the tokens to the user poolToken.issue(msg.sender, amount); // return the amount of pool tokens issued return amount; } /** * @dev get the amount of pool tokens to mint for the caller * and the amount of reserve tokens to transfer from the caller * * @param amounts amount of each reserve token * @param balances balance of each reserve token * @param totalSupply total supply of pool tokens * * @return amount of pool tokens to mint for the caller * @return amount of reserve tokens to transfer from the caller */ function addLiquidityAmounts( IReserveToken[] memory, /* reserves */ uint256[] memory amounts, uint256[2] memory balances, uint256 totalSupply ) private pure returns (uint256, uint256[2] memory) { uint256 index = amounts[0].mul(balances[1]) < amounts[1].mul(balances[0]) ? 0 : 1; uint256 amount = fundSupplyAmount(totalSupply, balances[index], amounts[index]); uint256[2] memory newAmounts = [fundCost(totalSupply, balances[0], amount), fundCost(totalSupply, balances[1], amount)]; return (amount, newAmounts); } /** * @dev decreases the pool's liquidity and burns the caller's shares in the pool * * @param amount token amount * @param reserves address of each reserve token * @param minReturnAmounts minimum return-amount of each reserve token * * @return the amount of each reserve token granted for the given amount of pool tokens */ function removeLiquidity( uint256 amount, IReserveToken[] memory reserves, uint256[] memory minReturnAmounts ) external nonReentrant active returns (uint256[] memory) { // verify the user input bool inputRearranged = verifyLiquidityInput(reserves, minReturnAmounts, amount); // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply BEFORE destroying the user tokens uint256 totalSupply = poolToken.totalSupply(); // destroy the user tokens poolToken.destroy(msg.sender, amount); uint256 newPoolTokenSupply = totalSupply.sub(amount); uint256[2] memory prevReserveBalances; uint256[2] memory newReserveBalances; // process the network fees and get the reserve balances (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0); uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(amount, totalSupply, prevReserveBalances); for (uint256 i = 0; i < 2; i++) { IReserveToken reserveToken = reserves[i]; uint256 reserveAmount = reserveAmounts[i]; require(reserveAmount >= minReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT"); // save the new reserve balance newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount); // transfer each one of the reserve amounts from the pool to the user reserveToken.safeTransfer(msg.sender, reserveAmount); emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply); } // set the reserve balances setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]); // set the reserve balances product _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1]; if (inputRearranged) { uint256 tempReserveAmount = reserveAmounts[0]; reserveAmounts[0] = reserveAmounts[1]; reserveAmounts[1] = tempReserveAmount; } // return the amount of each reserve token granted for the given amount of pool tokens return reserveAmounts; } /** * @dev given the amount of one of the reserve tokens to add liquidity of, * returns the required amount of each one of the other reserve tokens * since an empty pool can be funded with any list of non-zero input amounts, * this function assumes that the pool is not empty (has already been funded) * * @param reserves address of each reserve token * @param index index of the relevant reserve token * @param amount amount of the relevant reserve token * * @return the required amount of each one of the reserve tokens */ function addLiquidityCost( IReserveToken[] memory reserves, uint256 index, uint256 amount ) external view returns (uint256[] memory) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); uint256 supplyAmount = fundSupplyAmount(totalSupply, baseBalances[index], amount); uint256[] memory reserveAmounts = new uint256[](2); reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], supplyAmount); reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], supplyAmount); return reserveAmounts; } /** * @dev returns the amount of pool tokens entitled for given amounts of reserve tokens * since an empty pool can be funded with any list of non-zero input amounts, * this function assumes that the pool is not empty (has already been funded) * * @param reserves address of each reserve token * @param amounts amount of each reserve token * * @return the amount of pool tokens entitled for the given amounts of reserve tokens */ function addLiquidityReturn(IReserveToken[] memory reserves, uint256[] memory amounts) external view returns (uint256) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); (uint256 amount, ) = addLiquidityAmounts(reserves, amounts, baseBalances, totalSupply); return amount; } /** * @dev returns the amount of each reserve token entitled for a given amount of pool tokens * * @param amount amount of pool tokens * @param reserves address of each reserve token * * @return the amount of each reserve token entitled for the given amount of pool tokens */ function removeLiquidityReturn(uint256 amount, IReserveToken[] memory reserves) external view returns (uint256[] memory) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); return removeLiquidityReserveAmounts(amount, totalSupply, baseBalances); } /** * @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens * we take this input in order to allow specifying the corresponding reserve amounts in any order * this function rearranges the input arrays according to the converter's array of reserve tokens * * @param reserves array of reserve tokens * @param amounts array of reserve amounts * @param amount token amount * * @return true if the function has rearranged the input arrays; false otherwise */ function verifyLiquidityInput( IReserveToken[] memory reserves, uint256[] memory amounts, uint256 amount ) private view returns (bool) { require(validReserveAmounts(amounts) && amount > 0, "ERR_ZERO_AMOUNT"); uint256 reserve0Id = _reserveIds[reserves[0]]; uint256 reserve1Id = _reserveIds[reserves[1]]; if (reserve0Id == 2 && reserve1Id == 1) { IReserveToken tempReserveToken = reserves[0]; reserves[0] = reserves[1]; reserves[1] = tempReserveToken; uint256 tempReserveAmount = amounts[0]; amounts[0] = amounts[1]; amounts[1] = tempReserveAmount; return true; } require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE"); return false; } /** * @dev checks whether or not both reserve amounts are larger than zero * * @param amounts array of reserve amounts * * @return true if both reserve amounts are larger than zero; false otherwise */ function validReserveAmounts(uint256[] memory amounts) private pure returns (bool) { return amounts[0] > 0 && amounts[1] > 0; } /** * @dev returns the amount of each reserve token entitled for a given amount of pool tokens * * @param amount amount of pool tokens * @param totalSupply total supply of pool tokens * @param balances balance of each reserve token * * @return the amount of each reserve token entitled for the given amount of pool tokens */ function removeLiquidityReserveAmounts( uint256 amount, uint256 totalSupply, uint256[2] memory balances ) private pure returns (uint256[] memory) { uint256[] memory reserveAmounts = new uint256[](2); reserveAmounts[0] = liquidateReserveAmount(totalSupply, balances[0], amount); reserveAmounts[1] = liquidateReserveAmount(totalSupply, balances[1], amount); return reserveAmounts; } /** * @dev dispatches token rate update events for the reserve tokens and the pool token * * @param sourceToken address of the source reserve token * @param targetToken address of the target reserve token * @param sourceBalance balance of the source reserve token * @param targetBalance balance of the target reserve token */ function dispatchTokenRateUpdateEvents( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceBalance, uint256 targetBalance ) private { // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply of pool tokens uint256 poolTokenSupply = poolToken.totalSupply(); // dispatch token rate update event for the reserve tokens emit TokenRateUpdate(address(sourceToken), address(targetToken), targetBalance, sourceBalance); // dispatch token rate update events for the pool token emit TokenRateUpdate(address(poolToken), address(sourceToken), sourceBalance, poolTokenSupply); emit TokenRateUpdate(address(poolToken), address(targetToken), targetBalance, poolTokenSupply); } function encodeReserveBalance(uint256 balance, uint256 id) private pure returns (uint256) { assert(balance <= MAX_UINT128 && (id == 1 || id == 2)); return balance << ((id - 1) * 128); } function decodeReserveBalance(uint256 balances, uint256 id) private pure returns (uint256) { assert(id == 1 || id == 2); return (balances >> ((id - 1) * 128)) & MAX_UINT128; } function encodeReserveBalances( uint256 balance0, uint256 id0, uint256 balance1, uint256 id1 ) private pure returns (uint256) { return encodeReserveBalance(balance0, id0) | encodeReserveBalance(balance1, id1); } function decodeReserveBalances( uint256 _balances, uint256 id0, uint256 id1 ) private pure returns (uint256, uint256) { return (decodeReserveBalance(_balances, id0), decodeReserveBalance(_balances, id1)); } function encodeAverageRateInfo( uint256 averageRateT, uint256 averageRateN, uint256 averageRateD ) private pure returns (uint256) { assert(averageRateT <= MAX_UINT32 && averageRateN <= MAX_UINT112 && averageRateD <= MAX_UINT112); return (averageRateT << 224) | (averageRateN << 112) | averageRateD; } function decodeAverageRateT(uint256 averageRateInfoData) private pure returns (uint256) { return averageRateInfoData >> 224; } function decodeAverageRateN(uint256 averageRateInfoData) private pure returns (uint256) { return (averageRateInfoData >> 112) & MAX_UINT112; } function decodeAverageRateD(uint256 averageRateInfoData) private pure returns (uint256) { return averageRateInfoData & MAX_UINT112; } /** * @dev returns the largest integer smaller than or equal to the square root of a given value * * @param x the given value * * @return the largest integer smaller than or equal to the square root of the given value */ function floorSqrt(uint256 x) private pure returns (uint256) { return x > 0 ? MathEx.floorSqrt(x) : 0; } function crossReserveTargetAmount( uint256 sourceReserveBalance, uint256 targetReserveBalance, uint256 sourceAmount ) private pure returns (uint256) { require(sourceReserveBalance > 0 && targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); return targetReserveBalance.mul(sourceAmount) / sourceReserveBalance.add(sourceAmount); } function crossReserveSourceAmount( uint256 sourceReserveBalance, uint256 targetReserveBalance, uint256 targetAmount ) private pure returns (uint256) { require(sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(targetAmount < targetReserveBalance, "ERR_INVALID_AMOUNT"); if (targetAmount == 0) { return 0; } return (sourceReserveBalance.mul(targetAmount) - 1) / (targetReserveBalance - targetAmount) + 1; } function fundCost( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); // special case for 0 amount if (amount == 0) { return 0; } return (amount.mul(balance) - 1) / supply + 1; } function fundSupplyAmount( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); // special case for 0 amount if (amount == 0) { return 0; } return amount.mul(supply) / balance; } function liquidateReserveAmount( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(amount <= supply, "ERR_INVALID_AMOUNT"); // special case for 0 amount if (amount == 0) { return 0; } // special case for liquidating the entire supply if (amount == supply) { return balance; } return amount.mul(balance) / supply; } /** * @dev returns the network wallet and fees * * @param reserveBalance0 1st reserve balance * @param reserveBalance1 2nd reserve balance * * @return the network wallet * @return the network fee on the 1st reserve * @return the network fee on the 2nd reserve */ function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1) private view returns ( ITokenHolder, uint256, uint256 ) { uint256 prevPoint = floorSqrt(_reserveBalancesProduct); uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1); if (prevPoint >= currPoint) { return (ITokenHolder(address(0)), 0, 0); } (ITokenHolder networkFeeWallet, uint32 networkFee) = INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams(); uint256 n = (currPoint - prevPoint) * networkFee; uint256 d = currPoint * PPM_RESOLUTION; return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d)); } /** * @dev deprecated since version 28, backward compatibility - use only for earlier versions */ function token() external view override returns (IConverterAnchor) { return _anchor; } /** * @dev deprecated, backward compatibility */ function transferTokenOwnership(address newOwner) external override ownerOnly { transferAnchorOwnership(newOwner); } /** * @dev deprecated, backward compatibility */ function acceptTokenOwnership() public override ownerOnly { acceptAnchorOwnership(); } /** * @dev deprecated, backward compatibility */ function connectors(IReserveToken reserveToken) external view override returns ( uint256, uint32, bool, bool, bool ) { uint256 reserveId = _reserveIds[reserveToken]; if (reserveId != 0) { return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true); } return (0, 0, false, false, false); } /** * @dev deprecated, backward compatibility */ function connectorTokens(uint256 index) external view override returns (IReserveToken) { return _reserveTokens[index]; } /** * @dev deprecated, backward compatibility */ function connectorTokenCount() external view override returns (uint16) { return reserveTokenCount(); } /** * @dev deprecated, backward compatibility */ function getConnectorBalance(IReserveToken reserveToken) external view override returns (uint256) { return reserveBalance(reserveToken); } /** * @dev deprecated, backward compatibility */ function getReturn( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount ) external view returns (uint256, uint256) { return targetAmountAndFee(sourceToken, targetToken, sourceAmount); } }
transfers reserve balances to a new converter during an upgrade can only be called by the converter upgraded which should be set at its owner newConverter address of the converter to receive the new amount/
function transferReservesOnUpgrade(address newConverter) external override nonReentrant ownerOnly only(CONVERTER_UPGRADER) { uint256 reserveCount = _reserveTokens.length; for (uint256 i = 0; i < reserveCount; ++i) { IReserveToken reserveToken = _reserveTokens[i]; reserveToken.safeTransfer(newConverter, reserveToken.balanceOf(address(this))); syncReserveBalance(reserveToken); } }
12,547,156
./full_match/97/0xfD77CC4b5f5A745481747e93167C9B114dA5d539/sources/project_/contracts/ForzaPresale.sol
Public view function to calculate amount of sale tokens returned if you buy using "amount" of "token" uint tokenDec = IERC20(token).decimals();
function getTokenAmount(address token, uint256 amount) public view returns (uint256) { uint256 amtOut; if(token != address(0)){ require(tokenWL[token] == true, "Presale: Token not whitelisted"); uint256 price = tokenPrices[token]; amtOut = amount.mul(10**saleTokenDec).div(price); } else{ amtOut = amount.mul(10**saleTokenDec).div(rate); } return amtOut; }
3,284,266
pragma solidity ^0.4.24; // File: contracts/library/SafeMath.sol /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } // File: contracts/library/NameFilter.sol library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } // File: contracts/library/MSFun.sol /** @title -MSFun- v0.2.4 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ _ _ _ _ _ _ _ _ _ _ *=(_) _ _ (_)==========_(_)(_)(_)(_)_==========(_)(_)(_)(_)(_)================================* * (_)(_) (_)(_) (_) (_) (_) _ _ _ _ _ _ * (_) (_)_(_) (_) (_)_ _ _ _ (_) _ _ (_) (_) (_)(_)(_)(_)_ * (_) (_) (_) (_)(_)(_)(_)_ (_)(_)(_)(_) (_) (_) (_) * (_) (_) _ _ _ (_) _ _ (_) (_) (_) (_) (_) _ _ *=(_)=========(_)=(_)(_)==(_)_ _ _ _(_)=(_)(_)==(_)======(_)_ _ _(_)_ (_)========(_)=(_)(_)==* * (_) (_) (_)(_) (_)(_)(_)(_) (_)(_) (_) (_)(_)(_) (_)(_) (_) (_)(_) * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ * * ┌──────────────────────────────────────────────────────────────────────┐ * │ MSFun, is an importable library that gives your contract the ability │ * │ add multiSig requirement to functions. │ * └──────────────────────────────────────────────────────────────────────┘ * ┌────────────────────┐ * │ Setup Instructions │ * └────────────────────┘ * (Step 1) import the library into your contract * * import "./MSFun.sol"; * * (Step 2) set up the signature data for msFun * * MSFun.Data private msData; * ┌────────────────────┐ * │ Usage Instructions │ * └────────────────────┘ * at the beginning of a function * * function functionName() * { * if (MSFun.multiSig(msData, required signatures, "functionName") == true) * { * MSFun.deleteProposal(msData, "functionName"); * * // put function body here * } * } * ┌────────────────────────────────┐ * │ Optional Wrappers For TeamJust │ * └────────────────────────────────┘ * multiSig wrapper function (cuts down on inputs, improves readability) * this wrapper is HIGHLY recommended * * function multiSig(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredSignatures(), _whatFunction));} * function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));} * * wrapper for delete proposal (makes code cleaner) * * function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} * ┌────────────────────────────┐ * │ Utility & Vanity Functions │ * └────────────────────────────┘ * delete any proposal is highly recommended. without it, if an admin calls a multiSig * function, with argument inputs that the other admins do not agree upon, the function * can never be executed until the undesirable arguments are approved. * * function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} * * for viewing who has signed a proposal & proposal data * * function checkData(bytes32 _whatFunction) onlyAdmins() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} * * lets you check address of up to 3 signers (address) * * function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} * * same as above but will return names in string format. * * function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} * ┌──────────────────────────┐ * │ Functions In Depth Guide │ * └──────────────────────────┘ * In the following examples, the Data is the proposal set for this library. And * the bytes32 is the name of the function. * * MSFun.multiSig(Data, uint256, bytes32) - Manages creating/updating multiSig * proposal for the function being called. The uint256 is the required * number of signatures needed before the multiSig will return true. * Upon first call, multiSig will create a proposal and store the arguments * passed with the function call as msgData. Any admins trying to sign the * function call will need to send the same argument values. Once required * number of signatures is reached this will return a bool of true. * * MSFun.deleteProposal(Data, bytes32) - once multiSig unlocks the function body, * you will want to delete the proposal data. This does that. * * MSFun.checkMsgData(Data, bytes32) - checks the message data for any given proposal * * MSFun.checkCount(Data, bytes32) - checks the number of admins that have signed * the proposal * * MSFun.checkSigners(data, bytes32, uint256) - checks the address of a given signer. * the uint256, is the log number of the signer (ie 1st signer, 2nd signer) */ library MSFun { //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DATA SETS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // contact data setup struct Data { mapping (bytes32 => ProposalData) proposal_; } struct ProposalData { // a hash of msg.data bytes32 msgData; // number of signers uint256 count; // tracking of wither admins have signed mapping (address => bool) admin; // list of admins who have signed mapping (uint256 => address) log; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MULTI SIG FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction) internal returns(bool) { // our proposal key will be a hash of our function name + our contracts address // by adding our contracts address to this, we prevent anyone trying to circumvent // the proposal's security via external calls. bytes32 _whatProposal = whatProposal(_whatFunction); // this is just done to make the code more readable. grabs the signature count uint256 _currentCount = self.proposal_[_whatProposal].count; // store the address of the person sending the function call. we use msg.sender // here as a layer of security. in case someone imports our contract and tries to // circumvent function arguments. still though, our contract that imports this // library and calls multisig, needs to use onlyAdmin modifiers or anyone who // calls the function will be a signer. address _whichAdmin = msg.sender; // prepare our msg data. by storing this we are able to verify that all admins // are approving the same argument input to be executed for the function. we hash // it and store in bytes32 so its size is known and comparable bytes32 _msgData = keccak256(msg.data); // check to see if this is a new execution of this proposal or not if (_currentCount == 0) { // if it is, lets record the original signers data self.proposal_[_whatProposal].msgData = _msgData; // record original senders signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) // also useful if the calling function wants to give something to a // specific signer. self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; // if we now have enough signatures to execute the function, lets // return a bool of true. we put this here in case the required signatures // is set to 1. if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } // if its not the first execution, lets make sure the msgData matches } else if (self.proposal_[_whatProposal].msgData == _msgData) { // msgData is a match // make sure admin hasnt already signed if (self.proposal_[_whatProposal].admin[_whichAdmin] == false) { // record their signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; } // if we now have enough signatures to execute the function, lets // return a bool of true. // we put this here for a few reasons. (1) in normal operation, if // that last recorded signature got us to our required signatures. we // need to return bool of true. (2) if we have a situation where the // required number of signatures was adjusted to at or lower than our current // signature count, by putting this here, an admin who has already signed, // can call the function again to make it return a true bool. but only if // they submit the correct msg data if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } } // deletes proposal signature data after successfully executing a multiSig function function deleteProposal(Data storage self, bytes32 _whatFunction) internal { //done for readability sake bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; //delete the admins votes & log. i know for loops are terrible. but we have to do this //for our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this. for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } //delete the rest of the data in the record delete self.proposal_[_whatProposal]; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // HELPER FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function whatProposal(bytes32 _whatFunction) private view returns(bytes32) { return(keccak256(abi.encodePacked(_whatFunction,this))); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // VANITY FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // returns a hashed version of msg.data sent by original signer for any given function function checkMsgData (Data storage self, bytes32 _whatFunction) internal view returns (bytes32 msg_data) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].msgData); } // returns number of signers for any given function function checkCount (Data storage self, bytes32 _whatFunction) internal view returns (uint256 signature_count) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].count); } // returns address of an admin who signed for any given function function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer) internal view returns (address signer) { require(_signer > 0, "MSFun checkSigner failed - 0 not allowed"); bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].log[_signer - 1]); } } // File: contracts/interface/PlayerBookReceiverInterface.sol interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff, uint8 _level) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } // File: contracts/PlayerBook.sol /* * -PlayerBook - v-x * ______ _ ______ _ *====(_____ \=| |===============================(____ \===============| |=============* * _____) )| | _____ _ _ _____ ____ ____) ) ___ ___ | | _ * | ____/ | | (____ || | | || ___ | / ___) | __ ( / _ \ / _ \ | |_/ ) * | | | | / ___ || |_| || ____|| | | |__) )| |_| || |_| || _ ( *====|_|=======\_)\_____|=\__ ||_____)|_|======|______/==\___/==\___/=|_|=\_)=========* * (____/ * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private Community_Wallet1 = 0x00839c9d56F48E17d410E94309C91B9639D48242; address private Community_Wallet2 = 0x53bB6E7654155b8bdb5C4c6e41C9f47Cd8Ed1814; MSFun.Data private msData; function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} function checkData(bytes32 _whatFunction) onlyDevs() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; uint256 rreward; //for rank board uint256 cost; //everyone charges per round uint32 round; //rank round number for players uint8 level; } event eveSuperPlayer(bytes32 _name, uint256 _pid, address _addr, uint8 _level); event eveResolve(uint256 _startBlockNumber, uint32 _roundNumber); event eveUpdate(uint256 _pID, uint32 _roundNumber, uint256 _roundCost, uint256 _cost); event eveDeposit(address _from, uint256 _value, uint256 _balance ); event eveReward(uint256 _pID, uint256 _have, uint256 _reward, uint256 _vault, uint256 _allcost, uint256 _lastRefrralsVault ); event eveWithdraw(uint256 _pID, address _addr, uint256 _reward, uint256 _balance ); event eveSetAffID(uint256 _pID, address _addr, uint256 _laff, address _affAddr ); mapping (uint8 => uint256) public levelValue_; //for super player uint256[] public superPlayers_; //rank board data uint256[] public rankPlayers_; uint256[] public rankCost_; //the eth of refrerrals uint256 public referralsVault_; //the last rank round refrefrrals uint256 public lastRefrralsVault_; //time per round, the ethernum generate one block per 15 seconds, it will generate 24*60*60/15 blocks per 24h uint256 constant public roundBlockCount_ = 5760; //the start block numnber when the rank board had been activted for first time uint256 public startBlockNumber_; //rank top 10 uint8 constant public rankNumbers_ = 10; //current round number uint32 public roundNumber_; //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { levelValue_[3] = 0.003 ether; levelValue_[2] = 0.3 ether; levelValue_[1] = 1.5 ether; // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. pID_ = 0; rankPlayers_.length = rankNumbers_; rankCost_.length = rankNumbers_; roundNumber_ = 0; startBlockNumber_ = block.number; referralsVault_ = 0; lastRefrralsVault_ =0; addSuperPlayer(0x008d20ea31021bb4C93F3051aD7763523BBb0481,"main",1); addSuperPlayer(0x00De30E1A0E82750ea1f96f6D27e112f5c8A352D,"go",1); // addSuperPlayer(0x26042eb2f06D419093313ae2486fb40167Ba349C,"jack",1); addSuperPlayer(0x8d60d529c435e2A4c67FD233c49C3F174AfC72A8,"leon",1); addSuperPlayer(0xF9f24b9a5FcFf3542Ae3361c394AD951a8C0B3e1,"zuopiezi",1); addSuperPlayer(0x9ca974f2c49d68bd5958978e81151e6831290f57,"cowkeys",1); addSuperPlayer(0xf22978ed49631b68409a16afa8e123674115011e,"vulcan",1); addSuperPlayer(0x00b22a1D6CFF93831Cf2842993eFBB2181ad78de,"neo",1); // addSuperPlayer(0x10a04F6b13E95Bf8cC82187536b87A8646f1Bd9d,"mydream",1); // addSuperPlayer(0xce7aed496f69e2afdb99979952d9be8a38ad941d,"uking",1); addSuperPlayer(0x43fbedf2b2620ccfbd33d5c735b12066ff2fcdc1,"agg",1); } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } // only player with reward modifier onlyHaveReward() { require(myReward() > 0); _; } // check address modifier validAddress( address addr ) { require(addr != address(0x0)); _; } //devs check modifier onlyDevs(){ require( //msg.sender == 0x00D8E8CCb4A29625D299798036825f3fa349f2b4 ||//for test msg.sender == 0x00A32C09c8962AEc444ABde1991469eD0a9ccAf7 || msg.sender == 0x00aBBff93b10Ece374B14abb70c4e588BA1F799F, "only dev" ); _; } //level check modifier isLevel(uint8 _level) { require(_level >= 0 && _level <= 3, "invalid level"); require(msg.value >= levelValue_[_level], "sorry request price less than affiliate level"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addSuperPlayer(address _addr, bytes32 _name, uint8 _level) private { pID_++; plyr_[pID_].addr = _addr; plyr_[pID_].name = _name; plyr_[pID_].names = 1; plyr_[pID_].level = _level; pIDxAddr_[_addr] = pID_; pIDxName_[_name] = pID_; plyrNames_[pID_][_name] = true; plyrNameList_[pID_][1] = _name; superPlayers_.push(pID_); //fire event emit eveSuperPlayer(_name,pID_,_addr,_level); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // BALANCE //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function balances() public view returns(uint256) { return (address(this).balance); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DEPOSIT //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function deposit() validAddress(msg.sender) external payable returns (bool) { if(msg.value>0){ referralsVault_ += msg.value; emit eveDeposit(msg.sender, msg.value, address(this).balance); return true; } return false; } function updateRankBoard(uint256 _pID,uint256 _cost) isRegisteredGame() validAddress(msg.sender) external { uint256 _affID = plyr_[_pID].laff; if(_affID<=0){ return ; } if(_cost<=0){ return ; } //just for level 3 player if(plyr_[_affID].level != 3){ return ; } uint256 _affReward = _cost.mul(5)/100; //calc round charge if( plyr_[_affID].round == roundNumber_ ){ //same round plyr_[_affID].cost += _affReward; } else{ //diffrent round plyr_[_affID].cost = _affReward; plyr_[_affID].round = roundNumber_; } //check board players bool inBoard = false; for( uint8 i=0; i<rankNumbers_; i++ ){ if( _affID == rankPlayers_[i] ){ //update inBoard = true; rankCost_[i] = plyr_[_affID].cost; break; } } if( inBoard == false ){ //find the min charge player uint256 minCost = plyr_[_affID].cost; uint8 minIndex = rankNumbers_; for( uint8 k=0; k<rankNumbers_; k++){ if( rankCost_[k] < minCost){ minIndex = k; minCost = rankCost_[k]; } } if( minIndex != rankNumbers_ ){ //replace rankPlayers_[minIndex] = _affID; rankCost_[minIndex] = plyr_[_affID].cost; } } emit eveUpdate( _affID,roundNumber_,plyr_[_affID].cost,_cost); } // function resolveRankBoard() //isRegisteredGame() validAddress(msg.sender) external { uint256 deltaBlockCount = block.number - startBlockNumber_; if( deltaBlockCount < roundBlockCount_ ){ return; } //update start block number startBlockNumber_ = block.number; // emit eveResolve(startBlockNumber_,roundNumber_); roundNumber_++; //reward uint256 allCost = 0; for( uint8 k=0; k<rankNumbers_; k++){ allCost += rankCost_[k]; } if( allCost > 0 ){ uint256 reward = 0; uint256 roundVault = referralsVault_.sub(lastRefrralsVault_); for( uint8 m=0; m<rankNumbers_; m++){ uint256 pid = rankPlayers_[m]; if( pid>0 ){ reward = (roundVault.mul(8)/10).mul(rankCost_[m])/allCost; lastRefrralsVault_ += reward; plyr_[pid].rreward += reward; emit eveReward(rankPlayers_[m],plyr_[pid].rreward, reward,referralsVault_,allCost, lastRefrralsVault_); } } } //reset rank data rankPlayers_.length=0; rankCost_.length=0; rankPlayers_.length=10; rankCost_.length=10; } /** * Withdraws all of the callers earnings. */ function myReward() public view returns(uint256) { uint256 pid = pIDxAddr_[msg.sender]; return plyr_[pid].rreward; } function withdraw() onlyHaveReward() isHuman() public { address addr = msg.sender; uint256 pid = pIDxAddr_[addr]; uint256 reward = plyr_[pid].rreward; //reset plyr_[pid].rreward = 0; //get reward addr.transfer(reward); // fire event emit eveWithdraw(pIDxAddr_[addr], addr, reward, balances()); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all, _level); } function registerNameXaddr(string _nameString, address _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you've updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff, 0); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff, 0); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all, uint8 _level) private { // if names already has been used, require that current msg sender owns the name if( pIDxName_[_name] == _pID && _pID !=0 ){ //level up must keep old name! if (_level >= plyr_[_pID].level ) { require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); } } else if (pIDxName_[_name] != 0){ require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); } // add name to player profile, registry, and name book plyr_[_pID].name = _name; plyr_[_pID].level = _level; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards Community_Wallet1.transfer(msg.value / 2); Community_Wallet2.transfer(msg.value / 2); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID, _level); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getPlayerLevel(uint256 _pID) external view returns (uint8) { return (plyr_[_pID].level); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function setPlayerAffID(uint256 _pID,uint256 _laff) isRegisteredGame() external { plyr_[_pID].laff = _laff; emit eveSetAffID(_pID, plyr_[_pID].addr, _laff, plyr_[_laff].addr); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); deleteProposal("addGame"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); for(uint8 i=0; i<superPlayers_.length; i++){ uint256 pid =superPlayers_[i]; if( pid > 0 ){ games_[gID_].receivePlayerInfo(pid, plyr_[pid].addr, plyr_[pid].name, 0, plyr_[pid].level); } } } function setRegistrationFee(uint256 _fee) onlyDevs() public { deleteProposal("setRegistrationFee"); registrationFee_ = _fee; } }
make sure name fees paid filter name + condition checks set up address set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
function registerNameXname(string _nameString, bytes32 _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } }
6,075,910
./partial_match/1/0x843bD7a811DC26874Cb2ad9F4A04a8652F65d8e6/sources/contracts/liquidity-protection/LiquidityProtection.sol
utility to add liquidity to a converter/
function _addLiquidity( ILiquidityPoolConverter converter, IReserveToken reserveToken1, IReserveToken reserveToken2, uint256 reserveAmount1, uint256 reserveAmount2, uint256 value ) internal { IReserveToken[] memory reserveTokens = new IReserveToken[](2); uint256[] memory amounts = new uint256[](2); reserveTokens[0] = reserveToken1; reserveTokens[1] = reserveToken2; amounts[0] = reserveAmount1; amounts[1] = reserveAmount2; }
3,560,931
// SPDX-License-Identifier: MIT pragma solidity 0.5.16; import "./SafeMath.sol"; import "./Token.sol"; /// @title Контракт ICO contract TokenCrowdSale { using SafeMath for uint256; address payable private owner; /// адрес владельца uint256 private _openingTime; /// время открытия ICO (Unix Timestamp) uint256 private _closingTime; /// время закрытия ICO (Unix Timestamp) /// @notice вклад в ICO mapping(address => uint256) private contributions; Token private token; /// сам токен uint256 private _rate; /// Сколько единиц токена вкладчик получит за 1 wei uint256 private _softCap; /// нижний потолок для успешного ICO (в wei) uint256 private _hardCap; /// верхний потолок (в wei) uint256 private _weiRaised; /// число собранных средств (в wei) bool private _allowRefunds = false; /// переменная для возврата средств в случае неуспешного ICO modifier onlyWhileOpen { require(block.timestamp >= _openingTime && block.timestamp <= _closingTime); _; } /// @notice Получить информацию о том, закрыт ли ICO function hasClosed() public view returns (bool) { return block.timestamp > _closingTime; } /// @notice Получить информацию о том, открыт ли ICO function hasOpen() public view returns(bool) { return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } constructor(Token _token, uint256 rate_, uint256 softCap_, uint256 hardCap_, uint256 openingTime_, uint256 closingTime_) public { _rate = rate_; token = _token; _softCap = softCap_; _hardCap = hardCap_; owner = msg.sender; _openingTime = openingTime_; _closingTime = closingTime_; } /// @notice Получить нижний границу для успешного ICO function softCap() public view returns(uint256) { return _softCap; } /// @notice Получить верхнюю границу сборов function hardCap() public view returns(uint256) { return _hardCap; } /// @notice Получить время открытия ICO function openingTime() public view returns(uint256) { return _openingTime; } /// @notice Получить время закрытия ICO function closingTime() public view returns(uint256) { return _closingTime; } /// @notice Получить вклад в ICO /// @param _investor адрес инвестора function contribution(address _investor) public view returns(uint256) { return contributions[_investor]; } /// @notice Получить сколько единиц токена вкладчик получит за 1 wei function rate() public view returns(uint256) { return _rate; } /// @notice Получить число собранных средств (в wei) function weiRased() public view returns(uint256) { return _weiRaised; } /// @notice Получить информацию о разрешении на вывод средств (случай неуспешного ICO) function allowRefunds() public view returns(bool) { return _allowRefunds; } /// @notice Функция для приема средств function() external payable { buyTokens(msg.sender); } /// @notice Купить токен /// @param _beneficiary адрес бенифициара (кому купленные токены переведутся) function buyTokens(address _beneficiary) onlyWhileOpen public payable returns (bool success) { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); require(_weiRaised.add(weiAmount) <= _hardCap, "The ceiling has already been reached"); // update state _weiRaised = _weiRaised.add(weiAmount); contributions[msg.sender] = contributions[msg.sender].add(msg.value); _processPurchase(_beneficiary, tokens); return true; } /// @notice Валидация данных для покупки function _preValidatePurchase(address _beneficiary,uint256 _weiAmount) internal pure { require(_beneficiary != address(0)); require(_weiAmount != 0); } /// @notice Доставка токенов бенифициару function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.mint(_beneficiary, _tokenAmount); } /// @notice Внутренняя функция продолжения процесса покупки токена function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /// @notice Получить число токенов, соответствующих сумме (в wei) /// @param _weiAmount сумма в wei function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(_rate); } /// @notice Разрешить вывод средств (ICO неуспешен) function enableRefunds() private { require(msg.sender == owner); _allowRefunds = true; } /// @notice Вывод средств с ICO (пользователь сам вызывает функцию) function refund() public returns (bool success) { require(allowRefunds(), 'Refunds is not allowed, ICO is in progress'); uint amount = contributions[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call // before `send` returns. contributions[msg.sender] = 0; if (!msg.sender.send(amount)) { // No need to call throw here, just reset the amount owing contributions[msg.sender] = amount; return false; } } return true; } /// @notice Закрытие ICO function finalization() public { require(msg.sender == owner, "Only owner can finalize ICO"); require(hasClosed(), "Crowdsale is still open"); if (goalReached()) { token.unpause_token(); token.finishMint(); owner.transfer(_weiRaised); } else { enableRefunds(); token.finishMint(); } } /// @notice Проверка достигнута ли цель function goalReached() public view returns (bool) { return _weiRaised >= _softCap; } }
Получить время закрытия ICO
function closingTime() public view returns(uint256) { return _closingTime; }
975,308
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor (address[] memory payees, uint256[] memory shares_) payable { // solhint-disable-next-line max-line-length require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive () external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = totalReceived * _shares[account] / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // 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); } 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // 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; } } }
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); } }
270
./partial_match/1/0x24dbc70b3B8c1800372Ea8F763e90e3d98935959/sources/PrivateSaleVesting.sol
Internal function that returns withdrawable amount. _account account to retrieve withdrawable for return amount available for withdrawal Last block that user withdrew. If never, its the startblock of the first tranche Loop tranches Skip this tranche if it has not started yet or if the last blocknumber was already withdrawn
function _withdrawable( address _account ) private view returns (uint256 amount) { amount = 0; uint256 lastWithdrawBlockNr = lastWithdrawBlocknr[_account] > 0 ? lastWithdrawBlocknr[_account] : tranches[0].startBlockNr; for (uint256 i = 0; i < tranches.length; i++) { if ( block.number < tranches[i].startBlockNr || lastWithdrawBlockNr > tranches[i].startBlockNr.add(tranches[i].blockCount) ) { continue; } uint256 depositRatio = (deposits[_account].mul(UNITS).div(depositsTotal)); uint256 trancheBlockAmount = tranches[i].amount.div(tranches[i].blockCount); } }
9,302,732
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; interface ISideEntranceLenderPool { function deposit() external payable; function withdraw() external; function flashLoan( uint256 amount ) external; } contract SideEntranceAttackContract is Ownable { ISideEntranceLenderPool pool; uint256 poolBalance; address payable attacker; function attack(ISideEntranceLenderPool _pool, address payable _attacker) public onlyOwner { pool = _pool; poolBalance = address(pool).balance; attacker = _attacker; pool.flashLoan(poolBalance); pool.withdraw(); bool sent = attacker.send(poolBalance); require(sent, "Failed to send ether"); } // function called by ISideEntranceLenderPool function execute() external payable { pool.deposit{value: poolBalance}(); } receive() external payable {} }
function called by ISideEntranceLenderPool
function execute() external payable { }
1,803,760
/** *Submitted for verification at Etherscan.io on 2022-01-14 */ /** *Submitted for verification at Etherscan.io on 2022-01-13 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol 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/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/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/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/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 pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity >=0.7.0 <0.9.0; contract Downdle is ERC721Enumerable, Ownable { event PaymentReleased(address to, uint256 amount); mapping(address => bool) whitelistedAddresses; address[3] private _shareholders; uint[3] private _shares; using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.01 ether; uint256 public mintCount = 0; uint256 public maxSupply = 3333; uint256 public maxMintAmount = 20; bool public paused = true; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function mint(uint256 _mintAmount) public payable { // uint256 supply = totalSupply(); require(!paused, "Mint is currently paused"); require(_mintAmount > 0, "Mint amount must be greater than or equal to one"); require(_mintAmount <= maxMintAmount, "Mint amount greater than max allowed per mint tx"); require(mintCount + _mintAmount <= maxSupply, "Mint amount will exceed available number of tokens"); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount, "Value does not match mint cost"); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, mintCount + i); } mintCount+=_mintAmount; } function walletOfOwner(address _owner) public view returns (uint256[] memory){ uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function getMintCount() external view returns (uint256){ return mintCount; } function burn(uint256 tokenId) public virtual { _burn(tokenId); } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function pause(bool _state) public onlyOwner { paused = _state; } modifier isWhitelisted(address _address) { require(whitelistedAddresses[_address], "You need to be whitelisted"); _; } function checkIsWalletWhitelisted() public view isWhitelisted(msg.sender) returns(bool){ return (true); } function whitelistMint(uint256 _mintAmount) public payable { require(!paused, "Mint is currently paused"); require(_mintAmount > 0, "Mint amount must be greater than or equal to one"); require(_mintAmount <= maxMintAmount, "Mint amount greater than max allowed per wallet"); require(mintCount + _mintAmount <= maxSupply, "Mint amount will exceed available number of tokens"); require(whitelistedAddresses[msg.sender], "Wallet is not whitelisted"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, mintCount + i); } mintCount+=_mintAmount; } function addWalletToWhiteList(address _addressToWhitelist) public onlyOwner { whitelistedAddresses[_addressToWhitelist] = true; } function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
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"); }
101,837
/** *Submitted for verification at Etherscan.io on 2022-03-17 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IBaseFee interface IBaseFee { function isCurrentBaseFeeAcceptable() external view returns (bool); } // Part: IConvexDeposit interface IConvexDeposit { // deposit into convex, receive a tokenized deposit. parameter to stake immediately (we always do this). function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); // burn a tokenized deposit (Convex deposit tokens) to receive curve lp tokens back function withdraw(uint256 _pid, uint256 _amount) external returns (bool); // give us info about a pool based on its pid function poolInfo(uint256) external view returns ( address, address, address, address, address, bool ); } // Part: IConvexRewards interface IConvexRewards { // strategy's staked balance in the synthetix staking contract function balanceOf(address account) external view returns (uint256); // read how much claimable CRV a strategy has function earned(address account) external view returns (uint256); // stake a convex tokenized deposit function stake(uint256 _amount) external returns (bool); // withdraw to a convex tokenized deposit, probably never need to use this function withdraw(uint256 _amount, bool _claim) external returns (bool); // withdraw directly to curve LP token, this is what we primarily use function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool); // claim rewards, with an option to claim extra rewards or not function getReward(address _account, bool _claimExtras) external returns (bool); // check if we have rewards on a pool function extraRewardsLength() external view returns (uint256); // if we have rewards, see what the address is function extraRewards(uint256 _reward) external view returns (address); // read our rewards token function rewardToken() external view returns (address); // check our reward period finish function periodFinish() external view returns (uint256); } // Part: IOracle interface IOracle { function latestAnswer() external view returns (uint256); } // Part: IRocketPoolDeposit interface IRocketPoolDeposit { function deposit() external payable; } // Part: IRocketPoolHelper interface IRocketPoolHelper { function getRocketDepositPoolAddress() external view returns (address); function getMinimumDepositSize() external view returns (uint256); function isRethFree(address _user) external view returns (bool); function rEthCanAcceptDeposit(uint256 _ethAmount) external view returns (bool); function deposit() external payable; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: ICurveFi interface ICurveFi is IERC20 { function get_virtual_price() external view returns (uint256); function coins(uint256) external view returns (address); function add_liquidity( // EURt uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // Compound, sAave uint256[2] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // Iron Bank, Aave uint256[3] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3Crv Metapools address pool, uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // Y and yBUSD uint256[4] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3pool uint256[3] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // sUSD uint256[4] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function exchange( // CRV-ETH and CVX-ETH uint256 from, uint256 to, uint256 _from_amount, uint256 _min_to_amount, bool use_eth ) external; function exchange( // sETH int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external payable returns (uint256); function balances(uint256) external view returns (uint256); function price_oracle() external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); // EURt function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3Crv Metapools function calc_token_amount( address _pool, uint256[4] calldata _amounts, bool _is_deposit ) external view returns (uint256); // sUSD, Y pool, etc function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3pool, Iron Bank, etc function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit) external view returns (uint256); function calc_withdraw_one_coin(uint256 amount, int128 i) external view returns (uint256); } // Part: IstETH interface IstETH is IERC20 { function submit(address _referral) external payable returns (uint256); } // Part: IwstETH interface IwstETH is IERC20 { function wrap(uint256 _amount) external returns (uint256); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: StrategyConvexBase abstract contract StrategyConvexBase is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // these should stay the same across different wants. // convex stuff IConvexDeposit internal constant depositContract = IConvexDeposit(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); // this is the deposit contract that all pools use, aka booster IConvexRewards public rewardsContract; // This is unique to each curve pool uint256 public pid; // this is unique to each pool // keepCRV stuff uint256 public keepCRV; // the percentage of CRV we re-lock for boost (in basis points) address internal constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter, we send some extra CRV here uint256 internal constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in basis points IERC20 internal constant crv = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 internal constant convexToken = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); IERC20 internal constant weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // keeper stuff uint256 public harvestProfitMin; // minimum size in USDT that we want to harvest uint256 public harvestProfitMax; // maximum size in USDT that we want to harvest uint256 public creditThreshold; // amount of credit in underlying tokens that will automatically trigger a harvest bool internal forceHarvestTriggerOnce; // only set this to true when we want to trigger our keepers to harvest for us bool internal forceTendTriggerOnce; // only set this to true when we want to trigger our keepers to tend for us bool internal harvestNow; // this tells us if we're currently harvesting or tending string internal stratName; // we use this to be able to adjust our strategy's name // convex-specific variables bool public claimRewards; // boolean if we should always claim rewards when withdrawing, usually withdrawAndUnwrap (generally this should be false) /* ========== CONSTRUCTOR ========== */ constructor(address _vault) public BaseStrategy(_vault) {} /* ========== VIEWS ========== */ function name() external view override returns (string memory) { return stratName; } function stakedBalance() public view returns (uint256) { // how much want we have staked in Convex return rewardsContract.balanceOf(address(this)); } function balanceOfWant() public view returns (uint256) { // balance of want sitting in our strategy return want.balanceOf(address(this)); } function claimableBalance() public view returns (uint256) { // how much CRV we can claim from the staking contract return rewardsContract.earned(address(this)); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(stakedBalance()); } /* ========== CONSTANT FUNCTIONS ========== */ // these should stay the same across different wants. function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _wantBal = balanceOfWant(); if (_amountNeeded > _wantBal) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdrawAndUnwrap( Math.min(_stakedBal, _amountNeeded.sub(_wantBal)), claimRewards ); } uint256 _withdrawnBal = balanceOfWant(); _liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal); _loss = _amountNeeded.sub(_liquidatedAmount); } else { // we have enough balance to cover the liquidation available return (_amountNeeded, 0); } } // fire sale, get rid of it all! function liquidateAllPositions() internal override returns (uint256) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { // don't bother withdrawing zero rewardsContract.withdrawAndUnwrap(_stakedBal, claimRewards); } return balanceOfWant(); } // in case we need to exit into the convex deposit token, this will allow us to do that // make sure to check claimRewards before this step if needed // plan to have gov sweep convex deposit tokens from strategy after this function withdrawToConvexDepositTokens() external onlyVaultManagers { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdraw(_stakedBal, claimRewards); } } // we don't want for these tokens to be swept out. We allow gov to sweep out cvx vault tokens; we would only be holding these if things were really, really rekt. function protectedTokens() internal view override returns (address[] memory) {} /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%. function setKeepCRV(uint256 _keepCRV) external onlyVaultManagers { require(_keepCRV <= 10_000); keepCRV = _keepCRV; } // We usually don't need to claim rewards on withdrawals, but might change our mind for migrations etc function setClaimRewards(bool _claimRewards) external onlyVaultManagers { claimRewards = _claimRewards; } // This allows us to manually harvest or tend with our keeper as needed function setForceTriggerOnce( bool _forceTendTriggerOnce, bool _forceHarvestTriggerOnce ) external onlyEmergencyAuthorized { forceTendTriggerOnce = _forceTendTriggerOnce; forceHarvestTriggerOnce = _forceHarvestTriggerOnce; } } // File: StrategyConvexRocketpool.sol contract StrategyConvexRocketpool is StrategyConvexBase { /* ========== STATE VARIABLES ========== */ // these will likely change across different wants. // Curve stuff ICurveFi public constant curve = ICurveFi(0x447Ddd4960d9fdBF6af9a790560d0AF76795CB08); // This is our pool specific to this vault. bool public checkEarmark; // this determines if we should check if we need to earmark rewards before harvesting bool public mintReth; // use this to determine if we are depositing wsteth or reth to our curve pool (we mint both directly from ETH) // use Curve to sell our CVX and CRV rewards to WETH ICurveFi internal constant crveth = ICurveFi(0x8301AE4fc9c624d1D396cbDAa1ed877821D7C511); // use curve's new CRV-ETH crypto pool to sell our CRV ICurveFi internal constant cvxeth = ICurveFi(0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4); // use curve's new CVX-ETH crypto pool to sell our CVX // stETH and rETH token contracts IstETH internal constant steth = IstETH(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84); IwstETH internal constant wsteth = IwstETH(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0); IERC20 internal constant reth = IERC20(0xae78736Cd615f374D3085123A210448E74Fc6393); // rocketpool helper contract IRocketPoolHelper public constant rocketPoolHelper = IRocketPoolHelper(0x5943910C2e88480584092C7B95A3FD762cAbc699); address internal referral = 0xD20Eb2390e675b000ADb8511F62B28404115A1a4; // referral address, use EOA to claim on L2 uint256 public lastTendTime; // this is the timestamp that our last tend was called /* ========== CONSTRUCTOR ========== */ constructor( address _vault, uint256 _pid, string memory _name ) public StrategyConvexBase(_vault) { // want = Curve LP want.approve(address(depositContract), type(uint256).max); convexToken.approve(address(cvxeth), type(uint256).max); crv.approve(address(crveth), type(uint256).max); // setup our rewards contract pid = _pid; // this is the pool ID on convex, we use this to determine what the reweardsContract address is (address lptoken, , , address _rewardsContract, , ) = depositContract.poolInfo(_pid); // set up our rewardsContract rewardsContract = IConvexRewards(_rewardsContract); // check that our LP token based on our pid matches our want require(address(lptoken) == address(want)); // set our strategy's name stratName = _name; // these are our approvals and path specific to this contract wsteth.approve(address(curve), type(uint256).max); reth.approve(address(curve), type(uint256).max); steth.approve(address(wsteth), type(uint256).max); // set our last tend time on deployment lastTendTime = block.timestamp; } /* ========== VARIABLE FUNCTIONS ========== */ // these will likely change across different wants. function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // turn on our toggle for harvests harvestNow = true; if (!mintReth) { // go through the claim, sell, and deposit process for wstETH rewardsContract.getReward(address(this), true); uint256 crvBalance = crv.balanceOf(address(this)); uint256 convexBalance = convexToken.balanceOf(address(this)); uint256 sendToVoter = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR); if (sendToVoter > 0) { crv.safeTransfer(voter, sendToVoter); } uint256 crvRemainder = crv.balanceOf(address(this)); // sell the rest of our CRV and our CVX for ETH and mint wstETH with it uint256 ethBalance = _sellCrvAndCvx(crvRemainder, convexBalance); if (ethBalance > 0) { mintWsteth(ethBalance); } uint256 wstethBalance = wsteth.balanceOf(address(this)); if (wstethBalance > 0) { curve.add_liquidity([0, wstethBalance], 0); } } uint256 rEthBalance = reth.balanceOf(address(this)); // if we're depositing via rETH, we will have already minted it, but double-check that it's unlocked if (rEthBalance > 0 && isRethFree()) { curve.add_liquidity([rEthBalance, 0], 0); } // debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio if (_debtOutstanding > 0) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdrawAndUnwrap( Math.min(_stakedBal, _debtOutstanding), claimRewards ); } uint256 _withdrawnBal = balanceOfWant(); _debtPayment = Math.min(_debtOutstanding, _withdrawnBal); } // serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately uint256 assets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; // if assets are greater than debt, things are working great! if (assets > debt) { _profit = assets.sub(debt); uint256 _wantBal = balanceOfWant(); if (_profit.add(_debtPayment) > _wantBal) { // this should only be hit following donations to strategy liquidateAllPositions(); } } // if assets are less than debt, we are in trouble else { _loss = debt.sub(assets); } // we're done harvesting, so reset our trigger if we used it forceHarvestTriggerOnce = false; } function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } if (harvestNow) { // Send all of our Curve pool tokens to be deposited uint256 _toInvest = balanceOfWant(); // deposit into convex and stake immediately but only if we have something to invest if (_toInvest > 0) { depositContract.deposit(pid, _toInvest, true); } // we're done with our harvest, so we turn our toggle back to false harvestNow = false; } else { if (mintReth) { // this is our tend call claimAndMintReth(); } // update our variable for tracking last tend time lastTendTime = block.timestamp; // we're done harvesting, so reset our trigger if we used it forceTendTriggerOnce = false; } } // Sells our CRV and CVX for ETH on Curve function _sellCrvAndCvx(uint256 _crvAmount, uint256 _convexAmount) internal returns (uint256 ethBalance) { if (_convexAmount > 0) { cvxeth.exchange(1, 0, _convexAmount, 0, true); } if (_crvAmount > 0) { crveth.exchange(1, 0, _crvAmount, 0, true); } ethBalance = address(this).balance; } // mint wstETH from ETH function mintWsteth(uint256 _amount) internal { steth.submit{value: _amount}(referral); uint256 stethBalance = steth.balanceOf(address(this)); wsteth.wrap(stethBalance); } // claim and swap our CRV and CVX for rETH function claimAndMintReth() internal { // this claims our CRV, CVX, and any extra tokens. rewardsContract.getReward(address(this), true); uint256 crvBalance = crv.balanceOf(address(this)); uint256 convexBalance = convexToken.balanceOf(address(this)); uint256 sendToVoter = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR); if (sendToVoter > 0) { crv.safeTransfer(voter, sendToVoter); } uint256 crvRemainder = crv.balanceOf(address(this)); // sell the rest of our CRV and our CVX for ETH uint256 toDeposit = _sellCrvAndCvx(crvRemainder, convexBalance); // deposit our rETH only if there's space, and if it's large enough. this will prevent keepers from tending as well if needed. require( rocketPoolHelper.rEthCanAcceptDeposit(toDeposit), "Deposit too large." ); require( toDeposit > rocketPoolHelper.getMinimumDepositSize(), "Deposit too small." ); // pull our most recent deposit contract address since it can be upgraded IRocketPoolDeposit rocketDepositPool = IRocketPoolDeposit(rocketPoolHelper.getRocketDepositPoolAddress()); rocketDepositPool.deposit{value: toDeposit}(); } // migrate our want token to a new strategy if needed, make sure to check claimRewards first // also send over any CRV or CVX that is claimed; for migrations we definitely want to claim function prepareMigration(address _newStrategy) internal override { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdrawAndUnwrap(_stakedBal, claimRewards); } crv.safeTransfer(_newStrategy, crv.balanceOf(address(this))); convexToken.safeTransfer( _newStrategy, convexToken.balanceOf(address(this)) ); } /* ========== KEEP3RS ========== */ // use this to determine when to harvest function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { // Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job. if (!isActive()) { return false; } if (!mintReth) { // only check if we need to earmark on vaults we know are problematic if (checkEarmark) { // don't harvest if we need to earmark convex rewards if (needsEarmarkReward()) { return false; } } // harvest if we have a profit to claim at our upper limit without considering gas price uint256 claimableProfit = claimableProfitInUsdt(); if (claimableProfit > harvestProfitMax) { return true; } // check if the base fee gas price is higher than we allow. if it is, block harvests. if (!isBaseFeeAcceptable()) { return false; } // harvest if we have a sufficient profit to claim, but only if our gas price is acceptable if (claimableProfit > harvestProfitMin) { return true; } // pull our last harvest StrategyParams memory params = vault.strategies(address(this)); // Should trigger if hasn't been called in a while. if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; } // check if the base fee gas price is higher than we allow. if it is, block harvests. if (isBaseFeeAcceptable()) { // trigger if we want to manually harvest, but not if we also triggered a tend (should realistically never happen). if (forceHarvestTriggerOnce) { if (forceTendTriggerOnce) { return false; } else { return true; } } // harvest our strategy's credit if it's above our threshold if (vault.creditAvailable() > creditThreshold) { return true; } // if have any rETH, then we want to harvest as soon as it's free to deposit into our curve pool if (isRethFree() && reth.balanceOf(address(this)) > 0) { return true; } } // otherwise, we don't harvest return false; } function tendTrigger(uint256 callCostinEth) public view override returns (bool) { // Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job. if (!isActive()) { return false; } // only check if we need to tend if we're minting rETH if (mintReth) { // only check if we need to earmark on vaults we know are problematic if (checkEarmark) { // don't tend if we need to earmark convex rewards if (needsEarmarkReward()) { return false; } } // harvest if we have a profit to claim at our upper limit without considering gas price uint256 claimableProfit = claimableProfitInUsdt(); if (claimableProfit > harvestProfitMax) { return true; } // check if the base fee gas price is higher than we allow. if it is, block harvests. if (!isBaseFeeAcceptable()) { return false; } // trigger if we want to manually harvest, but only if our gas price is acceptable if (forceTendTriggerOnce) { return true; } // harvest if we have a sufficient profit to claim, but only if our gas price is acceptable if (claimableProfit > harvestProfitMin) { return true; } // Should trigger if hasn't been called in a while. Running this based on harvest even though this is a tend call since a harvest should run ~5 mins after every tend. if (block.timestamp.sub(lastTendTime) >= maxReportDelay) return true; } // otherwise, we don't harvest return false; } // we will need to add rewards token here if we have them function claimableProfitInUsdt() internal view returns (uint256) { // calculations pulled directly from CVX's contract for minting CVX per CRV claimed uint256 totalCliffs = 1_000; uint256 maxSupply = 100 * 1_000_000 * 1e18; // 100mil uint256 reductionPerCliff = 100_000 * 1e18; // 100,000 uint256 supply = convexToken.totalSupply(); uint256 mintableCvx; uint256 cliff = supply.div(reductionPerCliff); uint256 _claimableBal = claimableBalance(); //mint if below total cliffs if (cliff < totalCliffs) { //for reduction% take inverse of current cliff uint256 reduction = totalCliffs.sub(cliff); //reduce mintableCvx = _claimableBal.mul(reduction).div(totalCliffs); //supply cap check uint256 amtTillMax = maxSupply.sub(supply); if (mintableCvx > amtTillMax) { mintableCvx = amtTillMax; } } // our chainlink oracle returns prices normalized to 8 decimals, we convert it to 6 IOracle ethOracle = IOracle(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); uint256 ethPrice = ethOracle.latestAnswer().div(1e2); // 1e8 div 1e2 = 1e6 uint256 crvPrice = crveth.price_oracle().mul(ethPrice).div(1e18); // 1e18 mul 1e6 div 1e18 = 1e6 uint256 cvxPrice = cvxeth.price_oracle().mul(ethPrice).div(1e18); // 1e18 mul 1e6 div 1e18 = 1e6 uint256 crvValue = crvPrice.mul(_claimableBal).div(1e18); // 1e6 mul 1e18 div 1e18 = 1e6 uint256 cvxValue = cvxPrice.mul(mintableCvx).div(1e18); // 1e6 mul 1e18 div 1e18 = 1e6 return crvValue.add(cvxValue); } // convert our keeper's eth cost into want, we don't need this anymore since we don't use baseStrategy harvestTrigger function ethToWant(uint256 _ethAmount) public view override returns (uint256) { return _ethAmount; } // check if the current baseFee is below our external target function isBaseFeeAcceptable() internal view returns (bool) { return IBaseFee(0xb5e1CAcB567d98faaDB60a1fD4820720141f064F) .isCurrentBaseFeeAcceptable(); } // this contains logic to check if it's been long enough since we minted our rETH to move it function isRethFree() public view returns (bool) { return rocketPoolHelper.isRethFree(address(this)); } // check if someone needs to earmark rewards on convex before keepers harvest again function needsEarmarkReward() public view returns (bool needsEarmark) { // check if there is any CRV we need to earmark uint256 crvExpiry = rewardsContract.periodFinish(); if (crvExpiry < block.timestamp) { return true; } } // include so our contract plays nicely with ether receive() external payable {} function sweepETH() public onlyGovernance { (bool success, ) = governance().call{value: address(this).balance}(""); require(success, "!FailedETHSweep"); } /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Set whether we mint rETH or wstETH function setMintReth(bool _mintReth) external onlyVaultManagers { mintReth = _mintReth; } // Min profit to start checking for harvests if gas is good, max will harvest no matter gas (both in USDT, 6 decimals). Credit threshold is in want token, and will trigger a harvest if credit is large enough. check earmark to look at convex's booster. function setHarvestTriggerParams( uint256 _harvestProfitMin, uint256 _harvestProfitMax, uint256 _creditThreshold, bool _checkEarmark ) external onlyVaultManagers { harvestProfitMin = _harvestProfitMin; harvestProfitMax = _harvestProfitMax; creditThreshold = _creditThreshold; checkEarmark = _checkEarmark; } // update our referral address as needed function setReferral(address _referral) external onlyVaultManagers { referral = _referral; } }
turn on our toggle for harvests go through the claim, sell, and deposit process for wstETH if we're depositing via rETH, we will have already minted it, but double-check that it's unlocked debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio if assets are greater than debt, things are working great! this should only be hit following donations to strategy if assets are less than debt, we are in trouble
function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { harvestNow = true; if (!mintReth) { rewardsContract.getReward(address(this), true); uint256 crvBalance = crv.balanceOf(address(this)); uint256 convexBalance = convexToken.balanceOf(address(this)); uint256 sendToVoter = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR); if (sendToVoter > 0) { crv.safeTransfer(voter, sendToVoter); } uint256 crvRemainder = crv.balanceOf(address(this)); if (ethBalance > 0) { mintWsteth(ethBalance); } uint256 wstethBalance = wsteth.balanceOf(address(this)); if (wstethBalance > 0) { curve.add_liquidity([0, wstethBalance], 0); } } uint256 rEthBalance = reth.balanceOf(address(this)); if (rEthBalance > 0 && isRethFree()) { curve.add_liquidity([rEthBalance, 0], 0); } if (_debtOutstanding > 0) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { rewardsContract.withdrawAndUnwrap( Math.min(_stakedBal, _debtOutstanding), claimRewards ); } uint256 _withdrawnBal = balanceOfWant(); _debtPayment = Math.min(_debtOutstanding, _withdrawnBal); } uint256 debt = vault.strategies(address(this)).totalDebt; if (assets > debt) { _profit = assets.sub(debt); uint256 _wantBal = balanceOfWant(); if (_profit.add(_debtPayment) > _wantBal) { liquidateAllPositions(); } } else { _loss = debt.sub(assets); } }
10,493,790
./partial_match/56/0x39CDdf63B777CcfCAE6609cB2EBA4eAD29FF81b7/sources/StrategyAutoCakeLP.sol
Takes out 4.5% as system fees from the rewards. 0.5% -> Call Fee 0.5% -> Treasury fee 0.5% -> Strategist fee 3.0% -> BIFI Holders/
function chargeFees() internal { uint256 toWbnb = IERC20(Auto).balanceOf(address(this)).mul(45).div(1000); IUniswapRouter(unirouter).swapExactTokensForTokens(toWbnb, 0, autoToWbnbRoute, address(this), now.add(600)); uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this)); uint256 callFee = wbnbBal.mul(CALL_FEE).div(MAX_FEE); IERC20(wbnb).safeTransfer(msg.sender, callFee); uint256 treasuryHalf = wbnbBal.mul(TREASURY_FEE).div(MAX_FEE).div(2); IERC20(wbnb).safeTransfer(treasury, treasuryHalf); IUniswapRouter(unirouter).swapExactTokensForTokens(treasuryHalf, 0, wbnbToBifiRoute, treasury, now.add(600)); uint256 rewardsFee = wbnbBal.mul(REWARDS_FEE).div(MAX_FEE); IERC20(wbnb).safeTransfer(rewards, rewardsFee); uint256 strategistFee = wbnbBal.mul(STRATEGIST_FEE).div(MAX_FEE); IERC20(wbnb).safeTransfer(strategist, strategistFee); }
11,050,884
pragma solidity ^0.4.17; contract KernelStorage { event KernelLog(string message); // ** KERNEL STORAGE API ** // These functions operate on the kernel storage. These functions can be // considered the kernel storage API, all storage reads and writes should // come through this API. Each storage item/location has 3 functions, _set*, // _get*, and _getPointer*. The _get and _set functions work directly on // the value, while _getPointer returns the storage location. _get and _set // rely on _getPointer in such a way that storage locations are defined via // the _getPointer functions. // _getPointer* functions. These are all defined together first. // Returns the storage key that holds the entry procedure name. function _getPointerEntryProcedure() pure internal returns (uint256) { return 0xffffffff04000000000000000000000000000000000000000000000000000000; } // Returns the storage key that holds the current procedure name. function _getPointerCurrentProcedure() pure internal returns (uint256) { return 0xffffffff03000000000000000000000000000000000000000000000000000000; } // Returns the storage key that holds the kernel address. function _getPointerKernelAddress() pure internal returns (uint256) { return 0xffffffff02000000000000000000000000000000000000000000000000000000; } // Return the storage key that holds the number of procedures in the list. function _getPointerProcedureTableLength() internal pure returns (uint256) { bytes5 directory = bytes5(0xffffffff01); return uint256(bytes32(directory)); } // Returns the storage key that holds the procedure data of procedure #idx // in the procedure list. idx starts at 1. function _getPointerProcHeapByIndex(uint192 idx) internal pure returns (uint256) { // TODO: annoying error condition, can we avoid it? if (idx == 0) { revert("0 is not a valid key index"); } bytes5 directory = bytes5(0xffffffff01); return uint256(bytes32(directory)) | (uint256(idx) << 24); } // Returns the storage key that holds the procedure data with the given // procedure name. function _getPointerProcHeapByName(uint192 name) internal pure returns (uint256) { bytes5 directory = bytes5(0xffffffff00); return uint256(bytes32(directory)) | (uint256(name) << 24); } // The storage key that holds the Procedure Index of a procedure with the // given procedure name. function _getPointerProcedureIndexOnHeap(uint192 name) internal pure returns (uint256) { uint256 pPointer = _getPointerProcHeapByName(name); // The procedure index is stored at position 1 return (pPointer+1); } // The storage key that holds the Ethereum Address of the code of a // procedure with the given procedure name. function _getPointerProcedureAddress(uint192 name) internal pure returns (uint256) { uint256 pPointer = _getPointerProcHeapByName(name); // The procedure index is stored at position 1 return (pPointer+1); } // The storage get and set functions function _get(uint256 pointer) internal view returns (uint256 val) { assembly { // Load Value val := sload(pointer) } } function _set(uint256 pointer, uint256 value) internal { assembly { sstore(pointer, value) } } // _get and _set functions function _getEntryProcedure() view internal returns (uint192 val) { uint256 storageKey = _getPointerEntryProcedure(); assembly { val := sload(storageKey) } return val; } function _setEntryProcedureRaw(uint192 procedureKey) internal { uint256 storageKey = _getPointerEntryProcedure(); assembly { sstore(storageKey,procedureKey) } } function _getCurrentProcedure() view internal returns (uint192 val) { uint256 storageKey = _getPointerCurrentProcedure(); assembly { val := sload(storageKey) } return val; } function _setCurrentProcedure(uint192 procedureKey) internal { uint256 storageKey = _getPointerCurrentProcedure(); assembly { sstore(storageKey,procedureKey) } } function _getKernelAddress() view internal returns (address val) { uint256 storageKey = _getPointerKernelAddress(); assembly { val := sload(storageKey) } return val; } function _setKernelAddress(address theAddress) internal { uint256 storageKey = _getPointerKernelAddress(); assembly { sstore(storageKey, theAddress) } } // _get and _set functions which use the _getPointer functions above. // Given a Procedure Name, return it's index in the Procedure List (i.e. its // Procedure Index). If the procedure is not in the list it will return a // Procedure Index of zero. Zero is not a valid Procedure Index. function _getProcedureIndex(uint192 name) internal view returns (uint192) { uint256 procedureIndexPointer = _getPointerProcedureIndexOnHeap(name); return uint192(_get(procedureIndexPointer)); } }
The storage key that holds the Procedure Index of a procedure with the given procedure name. The procedure index is stored at position 1
function _getPointerProcedureIndexOnHeap(uint192 name) internal pure returns (uint256) { uint256 pPointer = _getPointerProcHeapByName(name); return (pPointer+1); }
1,056,152
pragma solidity >=0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /**************************************************************************/ /* DATA VARIABLES */ /**************************************************************************/ address private contractOwner; // Account used to deploy contract address private firstAirline = 0xf17f52151EbEF6C7334FAD080c5704D77216b732; // Blocks all state changes throughout the contract if false bool private operational = true; /***********************************************/ /* AIRLINE VARIABLES */ /***********************************************/ mapping(address => bool) private authorizedCallers; uint256 authAirlines = 0; // Airlines authorized for consensus voting uint256 regAirlines = 0; // Airlines registered enum AirlineState { Init, Application, Registered, Funded } struct Airline { AirlineState status; string name; mapping(address => bool) voters; uint voteCount; } mapping(address => Airline) airlines; /***********************************************/ /* FLIGHT VARIABLES */ /***********************************************/ struct Flight { bool isRegistered; uint8 statusCode; uint256 departure; uint256 lastUpdate; address airline; string flightCode; } mapping(string => Flight) private flights; string[] registeredFlights; /***********************************************/ /* INSURANCE VARIABLES */ /***********************************************/ enum InsuranceState { Init, Active, Payable, Closed, Received } struct Insurance { InsuranceState status; uint256 insuranceAmount; } mapping(address=> mapping(string => Insurance)) insurances; mapping(address=> uint256) passengerBalances; uint private constant MAX_INSURANCE_AMOUNT = 1 ether; /**************************************************************************/ /* EVENT DEFININTIONS */ /**************************************************************************/ event ApprovalVoting (address airlineAddress, uint votes, uint regAirlines); event AirlineRegistered (address airlineAddress, uint regAirlines); event AirlineFunded (address airlineAddress); event FlightStatusProcessed(string flight, uint8 statusCode); event FlightRegistered(string flightCode); event InsurancePurchased(address insuree, string flight); event PayoutToInsuree(address insuree, string flight); event InsureePayout(address insuree); // event Bugfix(InsuranceState store, InsuranceState valid); /** * @dev Constructorstring * The deploying account becomes contractOwner * First airline gets registered */ constructor() public { contractOwner = msg.sender; // Add Firts Airline on Contract deployment airlines[firstAirline] = Airline({ status: AirlineState.Registered, name: "FirstAirline", voteCount: 0 }); regAirlines = regAirlines.add(1); // Add sample flights on Contract deployment /* bytes32 key1 = getFlightKey(firstAirline, "Flight1", now + 1 days); bytes32 key2 = getFlightKey(firstAirline, "Flight2", now + 2 days); bytes32 key3 = getFlightKey(firstAirline, "Flight3", now + 3 days); */ string memory f1 = "Flight1"; string memory f2 = "Flight2"; string memory f3 = "Flight3"; flights[f1]= Flight(true, 0, now + 1 days, now, firstAirline, f1); registeredFlights.push(f1); flights[f2]= Flight(true, 0, now + 2 days, now, firstAirline, f2); registeredFlights.push(f2); flights[f3]= Flight(true, 0, now + 3 days, now, firstAirline, f3); registeredFlights.push(f3); } /**************************************************************************/ /* FUNCTION MODIFIERS */ /**************************************************************************/ /** * @dev Modifier that requires the "operational" bool variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be * the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the an authorised "ContractCaller" * account to be the function caller */ modifier requireAuthorizedCaller() { require(authorizedCallers[msg.sender], "Caller is not authorised"); _; } /**************************************************************************/ /* UTILITY FUNCTIONS */ /**************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except * for this one will fail */ function setOperatingStatus(bool _mode) external requireContractOwner { operational = _mode; } /** * @dev Sets authorized ContractCaller Addresses * */ function authorizeCaller(address _authCaller, bool _status) external requireContractOwner { authorizedCallers[_authCaller] = _status; } /**************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /**************************************************************************/ function isFundedAirline(address _airline) external view returns (bool) { return (airlines[_airline].status == AirlineState.Funded); } // App.registerAirline() function isAirline(address _airline) external view returns (bool) { AirlineState status = airlines[_airline].status; if ( status == AirlineState.Registered || status == AirlineState.Funded) return true; } // App.registerAirline() function countRegisteredAirlines() external view returns (uint) { return regAirlines; } /// App.registerAirline() function countCurrentVotes(address _airline) external view returns (uint) { return airlines[_airline].voteCount; } // App.registerAirline() function doubleVoteCheck(address _airline, address _caller) external view returns (bool) { return airlines[_airline].voters[_caller]; } // Data.registerAirline() function airlineFirstAction(address _airline) internal view returns (bool) { return ( airlines[_airline].status == AirlineState.Init); } // App.modifier requireRegisteredFlight() , App.registerAirline() function flightRegistered(string _flightCode) external view returns (bool) { return (flights[_flightCode].isRegistered); } // **** function getpassengerBalance() requireAuthorizedCaller external view returns (uint256) { return passengerBalances[tx.origin]; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline( address _airline, string _name, address _caller, bool _registered ) requireAuthorizedCaller external { Airline storage airline = airlines[_airline]; // First Interaction with Contract if (airlineFirstAction(_airline)) { airline.status = AirlineState.Application; airline.name = _name; airline.voteCount = 0; } // Consensus requirement if (_registered) { airline.status = AirlineState.Registered; airline.voters[_caller] = true; airline.voteCount = airline.voteCount.add(1); regAirlines = regAirlines.add(1); emit AirlineRegistered(_airline, regAirlines); } else { airline.voters[_caller] = true; airline.voteCount = airline.voteCount.add(1); emit ApprovalVoting(_airline, airline.voteCount, regAirlines); } } function registerFlight( address _airline, uint256 _departure, string _flightCode ) requireAuthorizedCaller external { // Add registered flight flights[_flightCode] = Flight({ isRegistered: true, statusCode: 0, departure: _departure, lastUpdate: now, airline: _airline, flightCode: _flightCode }); registeredFlights.push(_flightCode); emit FlightRegistered (_flightCode); } function updateFlightStatus(string _flightCode, uint8 _statusCode) requireIsOperational requireAuthorizedCaller external { flights[_flightCode].statusCode = _statusCode; emit FlightStatusProcessed(flights[_flightCode].flightCode, _statusCode); } // **** /* function getFlightStatus(bytes32 _flightKey) requireAuthorizedCaller external view returns(uint8) { return registeredFlights.length; } */ // **** function getRegisteredFlightsCount() external view returns(uint256) { return registeredFlights.length; } // **** function getRegisteredFlight(uint256 _index) external view returns( uint256 index, bool isRegistered, uint8 statusCode, uint256 departure, address airline, string flightCode ) { Flight storage flight = flights[registeredFlights[_index]]; index = _index; isRegistered = flight.isRegistered; statusCode = flight.statusCode; departure = flight.departure; airline = flight.airline; flightCode = flight.flightCode; } // TODO: logic to app contract function getInsurance(string _flightCode) external view returns ( InsuranceState status, uint256 insuranceAmount, uint8 flightStatus, string flightCode ) { Insurance memory insurance = insurances[msg.sender][_flightCode]; require( insurance.status != InsuranceState.Init, "Insurance Policy does not exist" ); flightStatus = flights[_flightCode].statusCode; InsuranceState insuranceState = insurance.status; if (insuranceState != InsuranceState.Received) { if (flightStatus == 20 ) { insurance.status = InsuranceState.Payable; } else if (flightStatus == 0) { insurance.status = InsuranceState.Active; } else { insurance.status = InsuranceState.Closed; } } status = insurance.status; insuranceAmount = insurance.insuranceAmount; flightCode = _flightCode; } // **** function getBalance(address _insuree) external view returns (uint256 balance) { // mapping(address=> uint256) passengerBalances; return passengerBalances[_insuree]; } /** * @dev Buy insurance for a flight * */ function buyInsurance (string _flightCode, address _caller) requireIsOperational requireAuthorizedCaller external payable { Insurance storage insurance = insurances[_caller][_flightCode]; require( insurance.status == InsuranceState.Init, "Insurance Policy already exists" ); insurance.status = InsuranceState.Active; insurance.insuranceAmount = msg.value; emit InsurancePurchased(_caller, _flightCode); } /** * @dev Credits payouts to insurees */ function creditInsurees ( string _flightCode ) requireIsOperational external { // TODO: optimize require and InsuranceState Payable logic require( (insurances[msg.sender][_flightCode].status == InsuranceState.Active), "Insurance payout not due" ); require( flights[_flightCode].statusCode == 20, "stopped at statusCode"); uint256 balance = passengerBalances[msg.sender]; uint256 amount = insurances[msg.sender][_flightCode].insuranceAmount; // SafeMath converted 1.5x payout uint256 insurancePayout = amount.add(amount.div(2)); insurances[msg.sender][_flightCode].status = InsuranceState.Received; passengerBalances[msg.sender] = balance.add(insurancePayout); emit PayoutToInsuree(msg.sender, _flightCode); } /** * @dev Transfers eligible payout funds to insuree * */ function pay() requireIsOperational external { uint256 payout = passengerBalances[msg.sender]; require(payout > 0, "There is no Balance available for payout"); passengerBalances[msg.sender] = 0; msg.sender.transfer(payout); emit InsureePayout(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 * */ function fund(address _airline) requireIsOperational public payable { require( airlines[_airline].status == AirlineState.Registered, "Airline Status not correct" ); require(msg.value >= 10 ether, "Sended Value is less than 10 Ether"); airlines[_airline].status = AirlineState.Funded; authAirlines = authAirlines.add(1); emit AirlineFunded(_airline); } function getFlightKey( address _airline, string _flight, uint256 _timestamp ) pure internal returns (bytes32) { return keccak256(abi.encodePacked(_airline, _flight, _timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
App.registerAirline()
function isAirline(address _airline) external view returns (bool) { AirlineState status = airlines[_airline].status; if ( status == AirlineState.Registered || status == AirlineState.Funded) return true; }
13,103,975
/** *Submitted for verification at Etherscan.io on 2020-09-18 */ /** *Submitted for verification at Etherscan.io on 2020-09-18 */ // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol pragma solidity 0.5.7; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity 0.5.7; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: nexusmutual-contracts/contracts/NXMToken.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract NXMToken is IERC20 { using SafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, 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 canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @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) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function _transferFrom( address from, address to, uint256 value ) internal { _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); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io 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.5.7; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns(uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io 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.5.7; contract IMaster { function getLatestAddress(bytes2 _module) public view returns(address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: nexusmutual-contracts/contracts/INXMMaster.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns(bool); function isInternal(address _add) public view returns(bool); function isPause() public view returns(bool check); function isOwner(address _add) public view returns(bool); function isMember(address _add) public view returns(bool); function checkIsAuthToGoverned(address _add) public view returns(bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns(address _add); function dAppToken() public view returns(address _add); function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress); } // File: nexusmutual-contracts/contracts/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } // File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol pragma solidity ^0.5.7; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } // File: nexusmutual-contracts/contracts/TokenFunctions.sol /* Copyright (C) 2020 NexusMutual.io 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.5.7; contract TokenFunctions is Iupgradable { using SafeMath for uint; MCR internal m1; MemberRoles internal mr; NXMToken public tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; PoolData internal pd; IPooledStaking pooledStaking; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev Rewards stakers on purchase of cover on smart contract. * @param _contractAddress smart contract address. * @param _coverPriceNXM cover price in NXM. */ function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal { uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100); pooledStaking.accumulateReward(_contractAddress, rewardValue); } /** * @dev Deprecated in favor of burnStakedTokens */ function burnStakerLockedToken(uint, bytes4, uint) external { // noop } /** * @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed. * @param coverId cover id * @param coverCurrency cover currency * @param sumAssured amount of $curr to burn */ function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal { (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = m1.calculateTokenPrice(coverCurrency); uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); } /** * @dev Gets the total staked NXM tokens against * Smart contract by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function deprecated_getTotalStakedTokensOnSmartContract( address _stakedContractAddress ) external view returns(uint) { uint stakedAmount = 0; address stakerAddress; uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress); for (uint i = 0; i < staketLen; i++) { stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i); uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress, _stakedContractAddress, stakerIndex); stakedAmount = stakedAmount.add(currentlyStaked); } return stakedAmount; } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) { return _getUserLockedCNTokens(_of, _coverId); } /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns(uint amount) { for (uint i = 0; i < qd.getUserCoverLength(_of); i++) { amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i])); } } /** * @dev Returns amount of NXM Tokens locked as Cover Note against given coverId. * @param _coverId coverId of the cover. */ function getLockedCNAgainstCover(uint _coverId) external view returns(uint) { return _getLockedCNAgainstCover(_coverId); } /** * @dev Returns total amount of staked NXM Tokens on all smart contracts. * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) { uint stakedAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i); stakedAmount = stakedAmount.add(currentlyStaked); } amount = stakedAmount; } /** * @dev Returns total unlockable amount of staked NXM Tokens on all smart contract . * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllUnlockableStakedTokens( address _stakerAddress ) external view returns (uint amount) { uint unlockableAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = unlockableAmount.add( _deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress, scIndex)); } amount = unlockableAmount; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /** * @dev Gets the Token price in a given currency * @param curr Currency name. * @return price Token Price. */ function getTokenPrice(bytes4 curr) public view returns(uint price) { price = m1.calculateTokenPrice(curr); } /** * @dev Set the flag to check if cover note is deposited against the cover id * @param coverId Cover Id. */ function depositCN(uint coverId) public onlyInternal returns (bool success) { require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available"); td.setDepositCN(coverId, true); success = true; } /** * @param _of address of Member * @param _coverId Cover Id * @param _lockTime Pending Time + Cover Period 7*1 days */ function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal { uint timeStamp = now.add(_lockTime); uint coverValidUntil = qd.getValidityOfCover(_coverId); if (timeStamp >= coverValidUntil) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); tc.extendLockOf(_of, reason, timeStamp); } } /** * @dev to burn the deposited cover tokens * @param coverId is id of cover whose tokens have to be burned * @return the status of the successful burning */ function burnDepositCN(uint coverId) public onlyInternal returns (bool success) { address _of = qd.getCoverMemberAddress(coverId); uint amount; (amount, ) = td.depositedCN(coverId); amount = (amount.mul(50)).div(100); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); tc.burnLockedTokens(_of, reason, amount); success = true; } /** * @dev Unlocks covernote locked against a given cover * @param coverId id of cover */ function unlockCN(uint coverId) public onlyInternal { (, bool isDeposited) = td.depositedCN(coverId); require(!isDeposited,"Cover note is deposited and can not be released"); uint lockedCN = _getLockedCNAgainstCover(coverId); if (lockedCN != 0) { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) public { require(ms.checkIsAuthToGoverned(msg.sender)); tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to lock cover note tokens * @param coverNoteAmount is number of tokens to be locked * @param coverPeriod is cover period in concern * @param coverId is the cover id of cover in concern * @param _of address whose tokens are to be locked */ function lockCN( uint coverNoteAmount, uint coverPeriod, uint coverId, address _of ) public onlyInternal { uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp()); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); td.setDepositCNAmount(coverId, coverNoteAmount); tc.lockOf(_of, reason, coverNoteAmount, validity); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns(bool) { return now < tk.isLockedForMV(_of); } /** * @dev Internal function to gets amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress, _stakedContractAddress, _stakedContractIndex); } /** * @dev Function to gets unlockable amount of locked NXM * tokens, staked against smartcontract by index * @param stakerAddress address of staker * @param stakedContractAddress staked contract address * @param stakerIndex index of staking */ function deprecated_getStakerUnlockableTokensOnSmartContract ( address stakerAddress, address stakedContractAddress, uint stakerIndex ) public view returns (uint) { return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress, td.getStakerStakedContractIndex(stakerAddress, stakerIndex)); } /** * @dev releases unlockable staked tokens to staker */ function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause { uint unlockableAmount; address scAddress; bytes32 reason; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract( _stakerAddress, scAddress, scIndex); td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0); td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount); reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex)); tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount); } } /** * @dev to get tokens of staker locked before burning that are allowed to burn * @param stakerAdd is the address of the staker * @param stakedAdd is the address of staked contract in concern * @param stakerIndex is the staker index in concern * @return amount of unlockable tokens * @return amount of tokens that can burn */ function _deprecated_unlockableBeforeBurningAndCanBurn( address stakerAdd, address stakedAdd, uint stakerIndex ) public view returns (uint amount, uint canBurn) { uint dateAdd; uint initialStake; uint totalBurnt; uint ub; (, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex); canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays()); // Can't use SafeMaths for int. int v = int(initialStake - (canBurn) - (totalBurnt) - ( td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub)); uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract( stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex)); if (v < 0) { v = 0; } amount = uint(v); if (canBurn > currentLockedTokens.sub(amount).sub(ub)) { canBurn = currentLockedTokens.sub(amount).sub(ub); } } /** * @dev to get tokens of staker that are unlockable * @param _stakerAddress is the address of the staker * @param _stakedContractAddress is the address of staked contract in concern * @param _stakedContractIndex is the staked contract index in concern * @return amount of unlockable tokens */ function _deprecated_getStakerUnlockableTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { uint initialStake; uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); uint burnt; (, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex); uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex); uint currentStakedTokens; (, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, _stakedContractAddress, stakerIndex); amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt); } /** * @dev Internal function to get the amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function _deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) internal view returns (uint amount) { bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); amount = tc.tokensLocked(_stakerAddress, reason); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _coverId coverId of the cover. */ function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) { address coverHolder = qd.getCoverMemberAddress(_coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId)); return tc.tokensLockedAtTime(coverHolder, reason, now); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); return tc.tokensLockedAtTime(_of, reason, now); } /** * @dev Internal function to gets remaining amount of staked NXM tokens, * against smartcontract by index * @param _stakeAmount address of user * @param _stakeDays staked contract address * @param _validDays index of staking */ function _deprecated_calculateStakedTokens( uint _stakeAmount, uint _stakeDays, uint _validDays ) internal pure returns (uint amount) { if (_validDays > _stakeDays) { uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays); amount = (rf.mul(_stakeAmount)).div(100000); } else { amount = 0; } } /** * @dev Gets the total staked NXM tokens against Smart contract * by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function _deprecated_burnStakerTokenLockedAgainstSmartContract( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _amount ) internal { uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount); bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); tc.burnLockedTokens(_stakerAddress, reason, _amount); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol /* Copyright (C) 2017 GovBlocks.io 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.5.7; contract IMemberRoles { event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public; /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(address _memberAddress, uint _roleId, bool _active) public; /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _authorized New authorized address against role id function changeAuthorized(uint _roleId, address _authorized) public; /// @dev Return number of member roles function totalRoles() public view returns(uint256); /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress); /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberAddress.length Member length function numberOfMembers(uint _memberRoleId) public view returns(uint); /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address); /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory assignedRoles); /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool); } // File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol pragma solidity 0.5.7; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract IERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: nexusmutual-contracts/contracts/TokenController.sol /* Copyright (C) 2020 NexusMutual.io 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.5.7; contract TokenController is IERC1132, Iupgradable { using SafeMath for uint256; event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime = uint(30).mul(1 days); bytes32 private constant CLA = bytes32("CLA"); /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress('PS')); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) { require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address"); require(token.operatorTransfer(_from, _value), "Operator transfer failed"); require(token.transfer(_to, _value), "Internal transfer failed"); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(minCALockTime <= _time,"Should lock for minimum time"); // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(msg.sender, _reason, _amount, _time); return true; } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Extends lock for reason CLA for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); _extendLock(msg.sender, _reason, _time); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(_tokensLocked(msg.sender, _reason) > 0); token.operatorTransfer(msg.sender, _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity); return true; } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom (address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the unlockable tokens against CLA of a specified address * @param _of Address of user, claiming back unlockable tokens against CLA */ function unlock(address _of) public checkPause returns (uint256 unlockableTokens) { unlockableTokens = _tokensUnlockable(_of, CLA); if (unlockableTokens > 0) { locked[_of][CLA].claimed = true; emit Unlocked(_of, CLA, unlockableTokens); require(token.transfer(_of, unlockableTokens)); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MNCLT") { minCALockTime = val.mul(1 days); } else { revert("Invalid param code"); } } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total locked tokens at time * Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility * for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. * Does not take into account pending burns. * * @param _of member whose locked tokens are to be calculate * @param _time timestamp when the tokens should be locked */ function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time)); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0); require(_amount != 0); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } require(token.operatorTransfer(_of, _amount)); uint256 validUntil = now.add(_time); //solhint-disable-line locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } require(token.transfer(_of, _amount)); emit Unlocked(_of, _reason, _amount); } function _removeReason(address _of, bytes32 _reason) internal { uint len = lockReason[_of].length; for (uint i = 0; i < len; i++) { if (lockReason[_of][i] == _reason) { lockReason[_of][i] = lockReason[_of][len.sub(1)]; lockReason[_of].pop(); break; } } } } // File: nexusmutual-contracts/contracts/ClaimsData.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } // File: nexusmutual-contracts/contracts/PoolData.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract DSValue { function peek() public view returns (bytes32, bool); function read() public view returns (bytes32); } contract PoolData is Iupgradable { using SafeMath for uint; struct ApiId { bytes4 typeOf; bytes4 currency; uint id; uint64 dateAdd; uint64 dateUpd; } struct CurrencyAssets { address currAddress; uint baseMin; uint varMin; } struct InvestmentAssets { address currAddress; bool status; uint64 minHoldingPercX100; uint64 maxHoldingPercX100; uint8 decimals; } struct IARankDetails { bytes4 maxIACurr; uint64 maxRate; bytes4 minIACurr; uint64 minRate; } struct McrData { uint mcrPercx100; uint mcrEther; uint vFull; //Pool funds uint64 date; } IARankDetails[] internal allIARankDetails; McrData[] public allMCRData; bytes4[] internal allInvestmentCurrencies; bytes4[] internal allCurrencies; bytes32[] public allAPIcall; mapping(bytes32 => ApiId) public allAPIid; mapping(uint64 => uint) internal datewiseId; mapping(bytes16 => uint) internal currencyLastIndex; mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets; mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets; mapping(bytes4 => uint) internal caAvgRate; mapping(bytes4 => uint) internal iaAvgRate; address public notariseMCR; address public daiFeedAddress; uint private constant DECIMAL1E18 = uint(10) ** 18; uint public uniswapDeadline; uint public liquidityTradeCallbackTime; uint public lastLiquidityTradeTrigger; uint64 internal lastDate; uint public variationPercX100; uint public iaRatesTime; uint public minCap; uint public mcrTime; uint public a; uint public shockParameter; uint public c; uint public mcrFailTime; uint public ethVolumeLimit; uint public capReached; uint public capacityLimit; constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public { notariseMCR = _notariseAdd; daiFeedAddress = _daiFeedAdd; c = 5800000; a = 1028; mcrTime = 24 hours; mcrFailTime = 6 hours; allMCRData.push(McrData(0, 0, 0, 0)); minCap = 12000 * DECIMAL1E18; shockParameter = 50; variationPercX100 = 100; //1% iaRatesTime = 24 hours; //24 hours in seconds uniswapDeadline = 20 minutes; liquidityTradeCallbackTime = 4 hours; ethVolumeLimit = 4; capacityLimit = 10; allCurrencies.push("ETH"); allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0); allCurrencies.push("DAI"); allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0); allInvestmentCurrencies.push("ETH"); allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18); allInvestmentCurrencies.push("DAI"); allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18); } /** * @dev to set the maximum cap allowed * @param val is the new value */ function setCapReached(uint val) external onlyInternal { capReached = val; } /// @dev Updates the 3 day average rate of a IA currency. /// To be replaced by MakerDao's on chain rates /// @param curr IA Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal { iaAvgRate[curr] = rate; } /// @dev Updates the 3 day average rate of a CA currency. /// To be replaced by MakerDao's on chain rates /// @param curr Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal { caAvgRate[curr] = rate; } /// @dev Adds details of (Minimum Capital Requirement)MCR. /// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456) /// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model. function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal { allMCRData.push(McrData(mcrp, mcre, vf, time)); } /** * @dev Updates the Timestamp at which result of oracalize call is received. */ function updateDateUpdOfAPI(bytes32 myid) external onlyInternal { allAPIid[myid].dateUpd = uint64(now); } /** * @dev Saves the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal,quote,cover etc. for which oraclize call is made */ function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal { allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now)); } /** * @dev Stores the id return by the oraclize query. * Maintains record of all the Ids return by oraclize query. * @param myid Id return by the oraclize query. */ function addInAllApiCall(bytes32 myid) external onlyInternal { allAPIcall.push(myid); } /** * @dev Saves investment asset rank details. * @param maxIACurr Maximum ranked investment asset currency. * @param maxRate Maximum ranked investment asset rate. * @param minIACurr Minimum ranked investment asset currency. * @param minRate Minimum ranked investment asset rate. * @param date in yyyymmdd. */ function saveIARankDetails( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate, uint64 date ) external onlyInternal { allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate)); datewiseId[date] = allIARankDetails.length.sub(1); } /** * @dev to get the time for the laste liquidity trade trigger */ function setLastLiquidityTradeTrigger() external onlyInternal { lastLiquidityTradeTrigger = now; } /** * @dev Updates Last Date. */ function updatelastDate(uint64 newDate) external onlyInternal { lastDate = newDate; } /** * @dev Adds currency asset currency. * @param curr currency of the asset * @param currAddress address of the currency * @param baseMin base minimum in 10^18. */ function addCurrencyAssetCurrency( bytes4 curr, address currAddress, uint baseMin ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencies.push(curr); allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0); } /** * @dev Adds investment asset. */ function addInvestmentAssetCurrency( bytes4 curr, address currAddress, bool status, uint64 minHoldingPercX100, uint64 maxHoldingPercX100, uint8 decimals ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentCurrencies.push(curr); allInvestmentAssets[curr] = InvestmentAssets(currAddress, status, minHoldingPercX100, maxHoldingPercX100, decimals); } /** * @dev Changes base minimum of a given currency asset. */ function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].baseMin = baseMin; } /** * @dev changes variable minimum of a given currency asset. */ function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal { allCurrencyAssets[curr].varMin = varMin; } /** * @dev Changes the investment asset status. */ function changeInvestmentAssetStatus(bytes4 curr, bool status) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].status = status; } /** * @dev Changes the investment asset Holding percentage of a given currency. */ function changeInvestmentAssetHoldingPerc( bytes4 curr, uint64 minPercX100, uint64 maxPercX100 ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].minHoldingPercX100 = minPercX100; allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100; } /** * @dev Gets Currency asset token address. */ function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].currAddress = currAdd; } /** * @dev Changes Investment asset token address. */ function changeInvestmentAssetAddressAndDecimal( bytes4 curr, address currAdd, uint8 newDecimal ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].currAddress = currAdd; allInvestmentAssets[curr].decimals = newDecimal; } /// @dev Changes address allowed to post MCR. function changeNotariseAddress(address _add) external onlyInternal { notariseMCR = _add; } /// @dev updates daiFeedAddress address. /// @param _add address of DAI feed. function changeDAIfeedAddress(address _add) external onlyInternal { daiFeedAddress = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "MCRTIM") { val = mcrTime / (1 hours); } else if (code == "MCRFTIM") { val = mcrFailTime / (1 hours); } else if (code == "MCRMIN") { val = minCap; } else if (code == "MCRSHOCK") { val = shockParameter; } else if (code == "MCRCAPL") { val = capacityLimit; } else if (code == "IMZ") { val = variationPercX100; } else if (code == "IMRATET") { val = iaRatesTime / (1 hours); } else if (code == "IMUNIDL") { val = uniswapDeadline / (1 minutes); } else if (code == "IMLIQT") { val = liquidityTradeCallbackTime / (1 hours); } else if (code == "IMETHVL") { val = ethVolumeLimit; } else if (code == "C") { val = c; } else if (code == "A") { val = a; } } /// @dev Checks whether a given address can notaise MCR data or not. /// @param _add Address. /// @return res Returns 0 if address is not authorized, else 1. function isnotarise(address _add) external view returns(bool res) { res = false; if (_add == notariseMCR) res = true; } /// @dev Gets the details of last added MCR. /// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100). /// @return vFull Total Pool fund value in Ether used in the last full daily calculation. function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) { uint index = allMCRData.length.sub(1); return ( allMCRData[index].mcrPercx100, allMCRData[index].mcrEther, allMCRData[index].vFull, allMCRData[index].date ); } /// @dev Gets last Minimum Capital Requirement percentage of Capital Model /// @return val MCR% value,multiplied by 100. function getLastMCRPerc() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrPercx100; } /// @dev Gets last Ether price of Capital Model /// @return val ether value,multiplied by 100. function getLastMCREther() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrEther; } /// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model. function getLastVfull() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].vFull; } /// @dev Gets last Minimum Capital Requirement in Ether. /// @return date of MCR. function getLastMCRDate() external view returns(uint64 date) { date = allMCRData[allMCRData.length.sub(1)].date; } /// @dev Gets details for token price calculation. function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) { _a = a; _c = c; rate = _getAvgRate(curr, false); } /// @dev Gets the total number of times MCR calculation has been made. function getMCRDataLength() external view returns(uint len) { len = allMCRData.length; } /** * @dev Gets investment asset rank details by given date. */ function getIARankDetailsByDate( uint64 date ) external view returns( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate ) { uint index = datewiseId[date]; return ( allIARankDetails[index].maxIACurr, allIARankDetails[index].maxRate, allIARankDetails[index].minIACurr, allIARankDetails[index].minRate ); } /** * @dev Gets Last Date. */ function getLastDate() external view returns(uint64 date) { return lastDate; } /** * @dev Gets investment currency for a given index. */ function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) { return allInvestmentCurrencies[index]; } /** * @dev Gets count of investment currency. */ function getInvestmentCurrencyLen() external view returns(uint len) { return allInvestmentCurrencies.length; } /** * @dev Gets all the investment currencies. */ function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) { return allInvestmentCurrencies; } /** * @dev Gets All currency for a given index. */ function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) { return allCurrencies[index]; } /** * @dev Gets count of All currency. */ function getAllCurrenciesLen() external view returns(uint len) { return allCurrencies.length; } /** * @dev Gets all currencies */ function getAllCurrencies() external view returns(bytes4[] memory currencies) { return allCurrencies; } /** * @dev Gets currency asset details for a given currency. */ function getCurrencyAssetVarBase( bytes4 curr ) external view returns( bytes4 currency, uint baseMin, uint varMin ) { return ( curr, allCurrencyAssets[curr].baseMin, allCurrencyAssets[curr].varMin ); } /** * @dev Gets minimum variable value for currency asset. */ function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) { return allCurrencyAssets[curr].varMin; } /** * @dev Gets base minimum of a given currency asset. */ function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) { return allCurrencyAssets[curr].baseMin; } /** * @dev Gets investment asset maximum and minimum holding percentage of a given currency. */ function getInvestmentAssetHoldingPerc( bytes4 curr ) external view returns( uint64 minHoldingPercX100, uint64 maxHoldingPercX100 ) { return ( allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100 ); } /** * @dev Gets investment asset decimals. */ function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) { return allInvestmentAssets[curr].decimals; } /** * @dev Gets investment asset maximum holding percentage of a given currency. */ function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) { return allInvestmentAssets[curr].maxHoldingPercX100; } /** * @dev Gets investment asset minimum holding percentage of a given currency. */ function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) { return allInvestmentAssets[curr].minHoldingPercX100; } /** * @dev Gets investment asset details of a given currency */ function getInvestmentAssetDetails( bytes4 curr ) external view returns( bytes4 currency, address currAddress, bool status, uint64 minHoldingPerc, uint64 maxHoldingPerc, uint8 decimals ) { return ( curr, allInvestmentAssets[curr].currAddress, allInvestmentAssets[curr].status, allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100, allInvestmentAssets[curr].decimals ); } /** * @dev Gets Currency asset token address. */ function getCurrencyAssetAddress(bytes4 curr) external view returns(address) { return allCurrencyAssets[curr].currAddress; } /** * @dev Gets investment asset token address. */ function getInvestmentAssetAddress(bytes4 curr) external view returns(address) { return allInvestmentAssets[curr].currAddress; } /** * @dev Gets investment asset active Status of a given currency. */ function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; } /** * @dev Gets type of oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return _typeof It could be of type "quote","quotation","cover","claim" etc. */ function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].typeOf; } /** * @dev Gets ID associated to oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return id1 It could be the ID of "proposal","quotation","cover","claim" etc. */ function getIdOfApiId(bytes32 myid) external view returns(uint) { return allAPIid[myid].id; } /** * @dev Gets the Timestamp of a oracalize call. */ function getDateAddOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateAdd; } /** * @dev Gets the Timestamp at which result of oracalize call is received. */ function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateUpd; } /** * @dev Gets currency by oracalize id. */ function getCurrOfApiId(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].currency; } /** * @dev Gets ID return by the oraclize query of a given index. * @param index Index. * @return myid ID return by the oraclize query. */ function getApiCallIndex(uint index) external view returns(bytes32 myid) { myid = allAPIcall[index]; } /** * @dev Gets Length of API call. */ function getApilCallLength() external view returns(uint) { return allAPIcall.length; } /** * @dev Get Details of Oraclize API when given Oraclize Id. * @param myid ID return by the oraclize query. * @return _typeof ype of the query for which oraclize * call is made.("proposal","quote","quotation" etc.) */ function getApiCallDetails( bytes32 myid ) external view returns( bytes4 _typeof, bytes4 curr, uint id, uint64 dateAdd, uint64 dateUpd ) { return ( allAPIid[myid].typeOf, allAPIid[myid].currency, allAPIid[myid].id, allAPIid[myid].dateAdd, allAPIid[myid].dateUpd ); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MCRTIM") { _changeMCRTime(val * 1 hours); } else if (code == "MCRFTIM") { _changeMCRFailTime(val * 1 hours); } else if (code == "MCRMIN") { _changeMinCap(val); } else if (code == "MCRSHOCK") { _changeShockParameter(val); } else if (code == "MCRCAPL") { _changeCapacityLimit(val); } else if (code == "IMZ") { _changeVariationPercX100(val); } else if (code == "IMRATET") { _changeIARatesTime(val * 1 hours); } else if (code == "IMUNIDL") { _changeUniswapDeadlineTime(val * 1 minutes); } else if (code == "IMLIQT") { _changeliquidityTradeCallbackTime(val * 1 hours); } else if (code == "IMETHVL") { _setEthVolumeLimit(val); } else if (code == "C") { _changeC(val); } else if (code == "A") { _changeA(val); } else { revert("Invalid param code"); } } /** * @dev to get the average rate of currency rate * @param curr is the currency in concern * @return required rate */ function getCAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, false); } /** * @dev to get the average rate of investment rate * @param curr is the investment in concern * @return required rate */ function getIAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, true); } function changeDependentContractAddress() public onlyInternal {} /// @dev Gets the average rate of a CA currency. /// @param curr Currency Name. /// @return rate Average rate X 100(of last 3 days). function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) { if (curr == "DAI") { DSValue ds = DSValue(daiFeedAddress); rate = uint(ds.read()).div(uint(10) ** 16); } else if (isIA) { rate = iaAvgRate[curr]; } else { rate = caAvgRate[curr]; } } /** * @dev to set the ethereum volume limit * @param val is the new limit value */ function _setEthVolumeLimit(uint val) internal { ethVolumeLimit = val; } /// @dev Sets minimum Cap. function _changeMinCap(uint newCap) internal { minCap = newCap; } /// @dev Sets Shock Parameter. function _changeShockParameter(uint newParam) internal { shockParameter = newParam; } /// @dev Changes time period for obtaining new MCR data from external oracle query. function _changeMCRTime(uint _time) internal { mcrTime = _time; } /// @dev Sets MCR Fail time. function _changeMCRFailTime(uint _time) internal { mcrFailTime = _time; } /** * @dev to change the uniswap deadline time * @param newDeadline is the value */ function _changeUniswapDeadlineTime(uint newDeadline) internal { uniswapDeadline = newDeadline; } /** * @dev to change the liquidity trade call back time * @param newTime is the new value to be set */ function _changeliquidityTradeCallbackTime(uint newTime) internal { liquidityTradeCallbackTime = newTime; } /** * @dev Changes time after which investment asset rates need to be fed. */ function _changeIARatesTime(uint _newTime) internal { iaRatesTime = _newTime; } /** * @dev Changes the variation range percentage. */ function _changeVariationPercX100(uint newPercX100) internal { variationPercX100 = newPercX100; } /// @dev Changes Growth Step function _changeC(uint newC) internal { c = newC; } /// @dev Changes scaling factor. function _changeA(uint val) internal { a = val; } /** * @dev to change the capacity limit * @param val is the new value */ function _changeCapacityLimit(uint val) internal { capacityLimit = val; } } // File: nexusmutual-contracts/contracts/QuotationData.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover } enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested } struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns(uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns(address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns(uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns(uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns(uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns(uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns(uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns(uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns(address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } // File: nexusmutual-contracts/contracts/TokenData.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public { //solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns(uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns(uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns(bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } // File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol /* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! // Dummy contract only used to emit to end-user they are using wrong solc contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string memory _datasource) public returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice); function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } if (address(oraclize) != OAR.getAddress()) { oraclize = OraclizeI(OAR.getAddress()); } _; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { return oraclize_setNetwork(); _networkID; // silence the warning and remain backwards compatible } function oraclize_setNetworkName(string memory _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); oraclize_setNetworkName("eth_goerli"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 _myid, string memory _result) public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public { return; _myid; _result; _proof; // Silence compiler warnings } function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(0, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(_timestamp, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /* END ORACLIZE_API */ // File: nexusmutual-contracts/contracts/Quotation.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract Quotation is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; TokenController internal tc; TokenData internal td; Pool1 internal p1; PoolData internal pd; QuotationData internal qd; MCR internal m1; MemberRoles internal mr; bool internal locked; event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); mr = MemberRoles(ms.getLatestAddress("MR")); } function sendEther() public payable { } /** * @dev Expires a cover after a set period of time. * Changes the status of the Cover and reduces the current * sum assured of all areas in which the quotation lies * Unlocks the CN tokens of the cover. Updates the Total Sum Assured value. * @param _cid Cover Id. */ function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); } /** * @dev Checks if a cover should get expired/closed or not. * @param _cid Cover Index. * @return expire true if the Cover's time has expired, false otherwise. */ function checkCoverExpired(uint _cid) public view returns(bool expire) { expire = qd.getValidityOfCover(_cid) < uint64(now); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal { _removeSAFromCSA(_cid, _amount); } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] memory coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) public isMemberAndcheckPause { tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySign( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA, uint8 _v, bytes32 _r, bytes32 _s ) public view returns(bool) { require(smaratCA != address(0)); require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time"); bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA ) public view returns(bytes32) { return keccak256( abi.encodePacked( coverDetails[0], curr, coverPeriod, smaratCA, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev to get the status of recently holded coverID * @param userAdd is the user address in concern * @return the status of the concerned coverId */ function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } } /** * @dev to initiate the membership and the cover * @param smartCAdd is the smart contract address to make cover on * @param coverCurr is the currency used to make cover * @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM * @param coverPeriod is cover period for which cover is being bought * @param _v argument from vrs hash * @param _r argument from vrs hash * @param _s argument from vrs hash */ function initiateMembershipAndCover( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable checkPause { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(!ms.isMember(msg.sender)); require(qd.refundEligible(msg.sender) == false); uint joinFee = td.joiningFee(); uint totalFee = joinFee; if (coverCurr == "ETH") { totalFee = joinFee.add(coverDetails[1]); } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1])); } require(msg.value == totalFee); require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s)); qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod); qd.setRefundEligible(msg.sender, true); } /** * @dev to get the verdict of kyc process * @param status is the kyc status * @param _add is the address of member */ function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); } /** * @dev transfering Ethers to newly created quotation contract. */ function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy { uint amount = address(this).balance; IERC20 erc20; if (amount > 0) { // newAdd.transfer(amount); Quotation newQT = Quotation(newAdd); newQT.sendEther.value(amount)(); } uint currAssetLen = pd.getAllCurrenciesLen(); for (uint64 i = 1; i < currAssetLen; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); address currAddr = pd.getCurrencyAssetAddress(currName); erc20 = IERC20(currAddr); //solhint-disable-line if (erc20.balanceOf(address(this)) > 0) { require(erc20.transfer(newAdd, erc20.balanceOf(address(this)))); } } } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover ( //solhint-disable-line address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod ) internal { uint cid = qd.getCoverLength(); qd.addCover(coverPeriod, coverDetails[0], from, coverCurr, scAddress, coverDetails[1], coverDetails[2]); // if cover period of quote is less than 60 days. if (coverPeriod <= 60) { p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days))); } uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100); tc.mint(from, coverNoteAmount); tf.lockCN(coverNoteAmount, coverPeriod, cid, from); qd.addInTotalSumAssured(coverCurr, coverDetails[0]); qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]); tf.pushStakerRewards(scAddress, coverDetails[2]); } /** * @dev Makes a vover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) internal { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s)); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause { address _add; bytes4 coverCurr; (, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid); qd.subFromTotalSumAssured(coverCurr, _amount); qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount); } /** * @dev to trigger the kyc process * @param status is the kyc status * @param _add is the address of member */ function _kycTrigger(bool status, address _add) internal { uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1); uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen); address payable userAdd; address scAddress; bytes4 coverCurr; uint16 coverPeriod; uint[] memory coverDetails = new uint[](4); IERC20 erc20; (, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID); (, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID); require(qd.refundEligible(userAdd)); qd.setRefundEligible(userAdd, false); require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending)); uint joinFee = td.joiningFee(); if (status) { mr.payJoiningFee.value(joinFee)(userAdd); if (coverDetails[3] > now) { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass)); address poolAdd = ms.getLatestAddress("P1"); if (coverCurr == "ETH") { p1.sendEther.value(coverDetails[1])(); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(poolAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed"); _makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod); } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover)); if (coverCurr == "ETH") { userAdd.transfer(coverDetails[1]); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed"); } } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); uint totalRefund = joinFee; if (coverCurr == "ETH") { totalRefund = coverDetails[1].add(joinFee); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } userAdd.transfer(totalRefund); emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed"); } } } // File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol pragma solidity 0.5.7; contract Factory { function getExchange(address token) public view returns (address); function getToken(address exchange) public view returns (address); } contract Exchange { function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256); function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256); function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256); function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient) public payable returns (uint256); function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline) public payable returns (uint256); function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient) public payable returns (uint256); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddress ) public returns (uint256); function tokenToTokenTransferInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address recipient, address tokenAddress ) public returns (uint256); } // File: nexusmutual-contracts/contracts/Pool2.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract Pool2 is Iupgradable { using SafeMath for uint; MCR internal m1; Pool1 internal p1; PoolData internal pd; Factory internal factory; address public uniswapFactoryAddress; uint internal constant DECIMAL1E18 = uint(10) ** 18; bool internal locked; constructor(address _uniswapFactoryAdd) public { uniswapFactoryAddress = _uniswapFactoryAdd; factory = Factory(_uniswapFactoryAdd); } function() external payable {} event Liquidity(bytes16 typeOf, bytes16 functionName); event Rebalancing(bytes4 iaCurr, uint tokenAmount); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev to change the uniswap factory address * @param newFactoryAddress is the new factory address in concern * @return the status of the concerned coverId */ function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal { // require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender)); uniswapFactoryAddress = newFactoryAddress; factory = Factory(uniswapFactoryAddress); } /** * @dev On upgrade transfer all investment assets and ether to new Investment Pool * @param newPoolAddress New Investment Assest Pool address */ function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy { uint len = pd.getInvestmentCurrencyLen(); for (uint64 i = 1; i < len; i++) { bytes4 iaName = pd.getInvestmentCurrencyByIndex(i); _upgradeInvestmentPool(iaName, newPoolAddress); } if (address(this).balance > 0) { Pool2 newP2 = Pool2(newPoolAddress); newP2.sendEther.value(address(this).balance)(); } } /** * @dev Internal Swap of assets between Capital * and Investment Sub pool for excess or insufficient * liquidity conditions of a given currency. */ function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy { uint caBalance; uint baseMin; uint varMin; (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { _internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance); } else if (caBalance < uint(baseMin).add(varMin)) { _internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance); } } /** * @dev Saves a given investment asset details. To be called daily. * @param curr array of Investment asset name. * @param rate array of investment asset exchange rate. * @param date current date in yyyymmdd. */ function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit) external checkPause noReentrancy { bytes4 maxCurr; bytes4 minCurr; uint64 maxRate; uint64 minRate; //ONLY NOTARZIE ADDRESS CAN POST require(pd.isnotarise(msg.sender)); (maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate); pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date); pd.updatelastDate(date); uint len = curr.length; for (uint i = 0; i < len; i++) { pd.updateIAAvgRate(curr[i], rate[i]); } if (bit) //for testing purpose _rebalancingLiquidityTrading(maxCurr, maxRate); p1.saveIADetailsOracalise(pd.iaRatesTime()); } /** * @dev External Trade for excess or insufficient * liquidity conditions of a given currency. */ function externalLiquidityTrade() external onlyInternal { bool triggerTrade; bytes4 curr; bytes4 minIACurr; bytes4 maxIACurr; uint amount; uint minIARate; uint maxIARate; uint baseMin; uint varMin; uint caBalance; (maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate()); uint len = pd.getAllCurrenciesLen(); for (uint64 i = 0; i < len; i++) { curr = pd.getCurrenciesByIndex(i); (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18; triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount); } else if (caBalance < uint(baseMin).add(varMin)) { // insufficient amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance); triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount); } if (triggerTrade) { p1.triggerExternalLiquidityTrade(); } } } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); pd = PoolData(ms.getLatestAddress("PD")); p1 = Pool1(ms.getLatestAddress("P1")); } function sendEther() public payable { } /** * @dev Gets currency asset balance for a given currency name. */ function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) { if (_curr == "ETH") { caBalance = address(p1).balance; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); caBalance = erc20.balanceOf(address(p1)); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _transferInvestmentAsset( bytes4 _curr, address _transferTo, uint _amount ) internal { if (_curr == "ETH") { if (_amount > address(this).balance) _amount = address(this).balance; p1.sendEther.value(_amount)(); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (_amount > erc20.balanceOf(address(this))) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(_transferTo, _amount)); } } /** * @dev to perform rebalancing * @param iaCurr is the investment asset currency * @param iaRate is the investment asset rate */ function _rebalancingLiquidityTrading( bytes4 iaCurr, uint64 iaRate ) internal checkPause { uint amountToSell; uint totalRiskBal = pd.getLastVfull(); uint intermediaryEth; uint ethVol = pd.ethVolumeLimit(); totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18); Exchange exchange; if (totalRiskBal > 0) { amountToSell = ((totalRiskBal.mul(2).mul( iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000); amountToSell = (amountToSell.mul( 10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr))); intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000); } IERC20 erc20; erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr)); erc20.approve(address(exchange), amountToSell); exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice( amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { _transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell); } emit Rebalancing(iaCurr, amountToSell); } } /** * @dev Checks whether trading is required for a * given investment asset at a given exchange rate. */ function _checkTradeConditions( bytes4 curr, uint64 iaRate, uint totalRiskBal ) internal view returns(bool check) { if (iaRate > 0) { uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18); if (iaBalance > 0 && totalRiskBal > 0) { uint iaMax; uint iaMin; uint checkNumber; uint z; (iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr); z = pd.variationPercX100(); checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate)); if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) || (checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100))) check = true; //eligibleIA } } } /** * @dev Gets the investment asset rank. */ function _getIARank( bytes4 curr, uint64 rateX100, uint totalRiskPoolBalance ) internal view returns (int rhsh, int rhsl) //internal function { uint currentIAmaxHolding; uint currentIAminHolding; uint iaBalance = _getInvestmentAssetBalance(curr); (currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr); if (rateX100 > 0) { uint rhsf; rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100)); rhsh = int(rhsf - currentIAmaxHolding); rhsl = int(rhsf - currentIAminHolding); } } /** * @dev Calculates the investment asset rank. */ function _calculateIARank( bytes4[] memory curr, uint64[] memory rate ) internal view returns( bytes4 maxCurr, uint64 maxRate, bytes4 minCurr, uint64 minRate ) { int max = 0; int min = -1; int rhsh; int rhsl; uint totalRiskPoolBalance; (totalRiskPoolBalance, ) = m1.calVtpAndMCRtp(); uint len = curr.length; for (uint i = 0; i < len; i++) { rhsl = 0; rhsh = 0; if (pd.getInvestmentAssetStatus(curr[i])) { (rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance); if (rhsh > max || i == 0) { max = rhsh; maxCurr = curr[i]; maxRate = rate[i]; } if (rhsl < min || rhsl == 0 || i == 0) { min = rhsl; minCurr = curr[i]; minRate = rate[i]; } } } } /** * @dev to get balance of an investment asset * @param _curr is the investment asset in concern * @return the balance */ function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) { if (_curr == "ETH") { balance = address(this).balance; } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); balance = erc20.balanceOf(address(this)); } } /** * @dev Creates Excess liquidity trading order for a given currency and a given balance. */ function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { // require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender)); bytes4 minIACurr; // uint amount; (, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == minIACurr) { // amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18; p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2))); } else { p1.triggerExternalLiquidityTrade(); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. */ function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { bytes4 maxIACurr; uint amount; (maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == maxIACurr) { amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance); _transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); if ((maxIACurr == "ETH" && address(this).balance > 0) || (maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0)) p1.triggerExternalLiquidityTrade(); } } /** * @dev Creates External excess liquidity trading * order for a given currency and a given balance. * @param curr Currency Asset to Sell * @param minIACurr Investment Asset to Buy * @param amount Amount of Currency Asset to Sell */ function _externalExcessLiquiditySwap( bytes4 curr, bytes4 minIACurr, uint256 amount ) internal returns (bool trigger) { uint intermediaryEth; Exchange exchange; IERC20 erc20; uint ethVol = pd.ethVolumeLimit(); if (curr == minIACurr) { p1.transferCurrencyAsset(curr, amount); } else if (curr == "ETH" && minIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr))); if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit amount = (address(exchange).balance.mul(ethVol)).div(100); trigger = true; } p1.transferCurrencyAsset(curr, amount); exchange.ethToTokenSwapInput.value(amount) (exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now)); } else if (curr != "ETH" && minIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getTokenToEthInputPrice(amount); trigger = true; } p1.transferCurrencyAsset(curr, amount); // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } Exchange tmp = Exchange(factory.getExchange( pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) { intermediaryEth = address(tmp).balance.mul(ethVol).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } p1.transferCurrencyAsset(curr, amount); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); erc20.approve(address(exchange), amount); exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr)); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. * @param curr Currency Asset to buy * @param maxIACurr Investment Asset to sell * @param amount Amount of Investment Asset to sell */ function _externalInsufficientLiquiditySwap( bytes4 curr, bytes4 maxIACurr, uint256 amount ) internal returns (bool trigger) { Exchange exchange; IERC20 erc20; uint intermediaryEth; // uint ethVol = pd.ethVolumeLimit(); if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); intermediaryEth = exchange.getEthToTokenInputPrice(amount); if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getEthToTokenInputPrice(amount); trigger = true; } erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr)); if (intermediaryEth > erc20.balanceOf(address(this))) { intermediaryEth = erc20.balanceOf(address(this)); } // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), intermediaryEth); exchange.tokenToEthTransferInput(intermediaryEth, ( exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else if (curr != "ETH" && maxIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > address(this).balance) intermediaryEth = address(this).balance; if (intermediaryEth > (address(exchange).balance.mul (pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else { address currAdd = pd.getCurrencyAssetAddress(curr); exchange = Exchange(factory.getExchange(currAdd)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) { intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth); erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); uint maxIABal = erc20.balanceOf(address(this)); if (maxIAToSell > maxIABal) { maxIAToSell = maxIABal; intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); } amount = exchange.getEthToTokenInputPrice(intermediaryEth); erc20.approve(address(tmp), maxIAToSell); tmp.tokenToTokenTransferInput(maxIAToSell, ( amount.mul(995)).div(1000), ( intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _upgradeInvestmentPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } } // File: nexusmutual-contracts/contracts/Pool1.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract Pool1 is usingOraclize, Iupgradable { using SafeMath for uint; Quotation internal q2; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; Pool2 internal p2; PoolData internal pd; MCR internal m1; Claims public c1; TokenData internal td; bool internal locked; uint internal constant DECIMAL1E18 = uint(10) ** 18; // uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18; event Apiresult(address indexed sender, string msg, bytes32 myid); event Payout(address indexed to, uint coverId, uint tokens); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } function () external payable {} //solhint-disable-line /** * @dev Pays out the sum assured in case a claim is accepted * @param coverid Cover Id. * @param claimid Claim Id. * @return succ true if payout is successful, false otherwise. */ function sendClaimPayout( uint coverid, uint claimid, uint sumAssured, address payable coverHolder, bytes4 coverCurr ) external onlyInternal noReentrancy returns(bool succ) { uint sa = sumAssured.div(DECIMAL1E18); bool check; IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //Payout if (coverCurr == "ETH" && address(this).balance >= sumAssured) { // check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured); coverHolder.transfer(sumAssured); check = true; } else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) { erc20.transfer(coverHolder, sumAssured); check = true; } if (check == true) { q2.removeSAFromCSA(coverid, sa); pd.changeCurrencyAssetVarMin(coverCurr, pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured)); emit Payout(coverHolder, coverid, sumAssured); succ = true; } else { c1.setClaimStatus(claimid, 12); } _triggerExternalLiquidityTrade(); // p2.internalLiquiditySwap(coverCurr); tf.burnStakerLockedToken(coverid, coverCurr, sumAssured); } /** * @dev to trigger external liquidity trade */ function triggerExternalLiquidityTrade() external onlyInternal { _triggerExternalLiquidityTrade(); } ///@dev Oraclize call to close emergency pause. function closeEmergencyPause(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000); _saveApiDetails(myid, "EP", 0); } /// @dev Calls the Oraclize Query to close a given Claim after a given period of time. /// @param id Claim Id to be closed /// @param time Time (in seconds) after which Claims assessment voting needs to be closed function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000); _saveApiDetails(myid, "CLA", id); } /// @dev Calls Oraclize Query to expire a given Cover after a given period of time. /// @param id Quote Id to be expired /// @param time Time (in seconds) after which the cover should be expired function closeCoverOraclise(uint id, uint64 time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat( "http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000); _saveApiDetails(myid, "COV", id); } /// @dev Calls the Oraclize Query to initiate MCR calculation. /// @param time Time (in milliseconds) after which the next MCR calculation should be initiated function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0); _saveApiDetails(myid, "MCR", 0); } /// @dev Calls the Oraclize Query in case MCR calculation fails. /// @param time Time (in seconds) after which the next MCR calculation should be initiated function mcrOracliseFail(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000); _saveApiDetails(myid, "MCRF", id); } /// @dev Oraclize call to update investment asset rates. function saveIADetailsOracalise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0); _saveApiDetails(myid, "IARB", 0); } /** * @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool * @param newPoolAddress Address of the new Pool */ function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal { for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 caName = pd.getCurrenciesByIndex(i); _upgradeCapitalPool(caName, newPoolAddress); } if (address(this).balance > 0) { Pool1 newP1 = Pool1(newPoolAddress); newP1.sendEther.value(address(this).balance)(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { m1 = MCR(ms.getLatestAddress("MC")); tk = NXMToken(ms.tokenAddress()); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); pd = PoolData(ms.getLatestAddress("PD")); q2 = Quotation(ms.getLatestAddress("QT")); p2 = Pool2(ms.getLatestAddress("P2")); c1 = Claims(ms.getLatestAddress("CL")); td = TokenData(ms.getLatestAddress("TD")); } function sendEther() public payable { } /** * @dev transfers currency asset to an address * @param curr is the currency of currency asset to transfer * @param amount is amount of currency asset to transfer * @return boolean to represent success or failure */ function transferCurrencyAsset( bytes4 curr, uint amount ) public onlyInternal noReentrancy returns(bool) { return _transferCurrencyAsset(curr, amount); } /// @dev Handles callback of external oracle query. function __callback(bytes32 myid, string memory result) public { result; //silence compiler warning // owner will be removed from production build ms.delegateCallBack(myid); } /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause payable { require(msg.value == coverDetails[1]); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed"); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /// @dev Enables user to purchase NXM at the current token price. function buyToken() public payable isMember checkPause returns(bool success) { require(msg.value > 0); uint tokenPurchased = _getToken(address(this).balance, msg.value); tc.mint(msg.sender, tokenPurchased); success = true; } /// @dev Sends a given amount of Ether to a given address. /// @param amount amount (in wei) to send. /// @param _add Receiver's address. /// @return succ True if transfer is a success, otherwise False. function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) { require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern"); succ = _add.send(amount); } /** * @dev Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) { require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance"); require(!tf.isLockedForMemberVote(msg.sender), "Member voted"); require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit"); uint sellingPrice = _getWei(_amount); tc.burnFrom(msg.sender, _amount); msg.sender.transfer(sellingPrice); success = true; } /** * @dev gives the investment asset balance * @return investment asset balance */ function getInvestmentAssetBalance() public view returns (uint balance) { IERC20 erc20; uint currTokens; for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) { bytes4 currency = pd.getInvestmentCurrencyByIndex(i); erc20 = IERC20(pd.getInvestmentAssetAddress(currency)); currTokens = erc20.balanceOf(address(p2)); if (pd.getIAAvgRate(currency) > 0) balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency))); } balance = balance.add(address(p2).balance); } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) public view returns(uint weiToPay) { return _getWei(amount); } /** * @dev Returns the amount of token a buyer will get for corresponding wei * @param weiPaid Amount of wei * @return tokenToGet Amount of tokens the buyer will get */ function getToken(uint weiPaid) public view returns(uint tokenToGet) { return _getToken((address(this).balance).add(weiPaid), weiPaid); } /** * @dev to trigger external liquidity trade */ function _triggerExternalLiquidityTrade() internal { if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) { pd.setLastLiquidityTradeTrigger(); bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000); _saveApiDetails(myid, "ULT", 0); } } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param _amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function _getWei(uint _amount) internal view returns(uint weiToPay) { uint tokenPrice; uint weiPaid; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calVtpAndMCRtp(); while (_amount > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5% if (_amount <= td.priceStep().mul(DECIMAL1E18)) { weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18)); break; } else { _amount = _amount.sub(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18)); weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18); vtp = vtp.sub(weiPaid); weiToPay = weiToPay.add(weiPaid); } } } /** * @dev gives the token * @param _poolBalance is the pool balance * @param _weiPaid is the amount paid in wei * @return the token to get */ function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) { uint tokenPrice; uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18); uint tempTokens; uint superWeiSpent; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid)); require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero"); while (superWeiLeft > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tempTokens = superWeiLeft.div(tokenPrice); if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) { tokenToGet = tokenToGet.add(tempTokens); break; } else { tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18)); superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice); superWeiLeft = superWeiLeft.sub(superWeiSpent); vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18)); } } } /** * @dev Save the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal, quote, cover etc. for which oraclize call is made. */ function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal { pd.saveApiDetails(myid, _typeof, id); pd.addInAllApiCall(myid); } /** * @dev transfers currency asset * @param _curr is currency of asset to transfer * @param _amount is the amount to be transferred * @return boolean representing the success of transfer */ function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) { if (_curr == "ETH") { if (address(this).balance < _amount) _amount = address(this).balance; p2.sendEther.value(_amount)(); succ = true; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line if (erc20.balanceOf(address(this)) < _amount) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(address(p2), _amount)); succ = true; } } /** * @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade. */ function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } /** * @dev oraclize query * @param paramCount is number of paramters passed * @param timestamp is the current timestamp * @param datasource in concern * @param arg in concern * @param gasLimit required for query * @return id of oraclize query */ function _oraclizeQuery( uint paramCount, uint timestamp, string memory datasource, string memory arg, uint gasLimit ) internal returns (bytes32 id) { if (paramCount == 4) { id = oraclize_query(timestamp, datasource, arg, gasLimit); } else if (paramCount == 3) { id = oraclize_query(timestamp, datasource, arg); } else { id = oraclize_query(datasource, arg); } } } // File: nexusmutual-contracts/contracts/MCR.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract MCR is Iupgradable { using SafeMath for uint; Pool1 internal p1; PoolData internal pd; NXMToken internal tk; QuotationData internal qd; MemberRoles internal mr; TokenData internal td; ProposalCategory internal proposalCategory; uint private constant DECIMAL1E18 = uint(10) ** 18; uint private constant DECIMAL1E05 = uint(10) ** 5; uint private constant DECIMAL1E19 = uint(10) ** 19; uint private constant minCapFactor = uint(10) ** 21; uint public variableMincap; uint public dynamicMincapThresholdx100 = 13000; uint public dynamicMincapIncrementx100 = 100; event MCREvent( uint indexed date, uint blockNumber, bytes4[] allCurr, uint[] allCurrRates, uint mcrEtherx100, uint mcrPercx100, uint vFull ); /** * @dev Adds new MCR data. * @param mcrP Minimum Capital Requirement in percentage. * @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model. * @param onlyDate Date(yyyymmdd) at which MCR details are getting added. */ function addMCRData( uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate ) external checkPause { require(proposalCategory.constructorCheck()); require(pd.isnotarise(msg.sender)); if (mr.launched() && pd.capReached() != 1) { if (mcrP >= 10000) pd.setCapReached(1); } uint len = pd.getMCRDataLength(); _addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg); } /** * @dev Adds MCR Data for last failed attempt. */ function addLastMCRData(uint64 date) external checkPause onlyInternal { uint64 lastdate = uint64(pd.getLastMCRDate()); uint64 failedDate = uint64(date); if (failedDate >= lastdate) { uint mcrP; uint mcrE; uint vF; (mcrP, mcrE, vF, ) = pd.getLastMCR(); uint len = pd.getAllCurrenciesLen(); pd.pushMCRData(mcrP, mcrE, vF, date); for (uint j = 0; j < len; j++) { bytes4 currName = pd.getCurrenciesByIndex(j); pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName)); } emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF); // Oraclize call for next MCR calculation _callOracliseForMCR(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); tk = NXMToken(ms.tokenAddress()); mr = MemberRoles(ms.getLatestAddress("MR")); td = TokenData(ms.getLatestAddress("TD")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Gets total sum assured(in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns(uint amount) { uint len = pd.getAllCurrenciesLen(); for (uint i = 0; i < len; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); if (currName == "ETH") { amount = amount.add(qd.getTotalSumAssured(currName)); } else { if (pd.getCAAvgRate(currName) > 0) amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName))); } } } /** * @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether * and MCR% used in the Token Price Calculation. * @return vtp Pool Fund Value in Ether used for the Token Price Model * @return mcrtp MCR% used in the Token Price Model. */ function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { vtp = 0; IERC20 erc20; uint currTokens = 0; uint i; for (i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 currency = pd.getCurrenciesByIndex(i); erc20 = IERC20(pd.getCurrencyAssetAddress(currency)); currTokens = erc20.balanceOf(address(p1)); if (pd.getCAAvgRate(currency) > 0) vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency))); } vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance()); uint mcrFullperc; uint vFull; (mcrFullperc, , vFull, ) = pd.getLastMCR(); if (vFull > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); } } /** * @dev Calculates the Token Price of NXM in a given currency. * @param curr Currency name. */ function calculateStepTokenPrice( bytes4 curr, uint mcrtp ) public view onlyInternal returns(uint tokenPrice) { return _calculateTokenPrice(curr, mcrtp); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param curr Currency name. */ function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) { uint mcrtp; (, mcrtp) = _calVtpAndMCRtp(address(p1).balance); return _calculateTokenPrice(curr, mcrtp); } function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(address(p1).balance); } function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(poolBalance); } function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold) { minCap = (minCap.mul(minCapFactor)).add(variableMincap); uint lower = 0; if (vtp >= vF) { upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap } else { upperThreshold = vF.mul(120).mul(100).div((minCap)); } if (vtp > 0) { lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100); if(lower < minCap.mul(11).div(10)) lower = minCap.mul(11).div(10); } if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100 lowerThreshold = vtp.mul(100).mul(100).div(lower); } } /** * @dev Gets max numbers of tokens that can be sold at the moment. */ function getMaxSellTokens() public view returns(uint maxTokens) { uint baseMin = pd.getCurrencyAssetBaseMin("ETH"); uint maxTokensAccPoolBal; if (address(p1).balance > baseMin.mul(50).div(100)) { maxTokensAccPoolBal = address(p1).balance.sub( (baseMin.mul(50)).div(100)); } maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div( (calculateTokenPrice("ETH").mul(975)).div(1000)); uint lastMCRPerc = pd.getLastMCRPerc(); if (lastMCRPerc > 10000) maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000); if (maxTokens > maxTokensAccPoolBal) maxTokens = maxTokensAccPoolBal; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "DMCT") { val = dynamicMincapThresholdx100; } else if (code == "DMCI") { val = dynamicMincapIncrementx100; } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { dynamicMincapThresholdx100 = val; } else if (code == "DMCI") { dynamicMincapIncrementx100 = val; } else { revert("Invalid param code"); } } /** * @dev Calls oraclize query to calculate MCR details after 24 hours. */ function _callOracliseForMCR() internal { p1.mcrOraclise(pd.mcrTime()); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param _curr Currency name. * @return tokenPrice Token price. */ function _calculateTokenPrice( bytes4 _curr, uint mcrtp ) internal view returns(uint tokenPrice) { uint getA; uint getC; uint getCAAvgRate; uint tokenExponentValue = td.tokenExponent(); // uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp)); uint max = mcrtp ** tokenExponentValue; uint dividingFactor = tokenExponentValue.mul(4); (getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr); uint mcrEth = pd.getLastMCREther(); getC = getC.mul(DECIMAL1E18); tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor); tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05)); tokenPrice = tokenPrice.mul(getCAAvgRate * 10); tokenPrice = (tokenPrice).div(10**3); } /** * @dev Adds MCR Data. Checks if MCR is within valid * thresholds in order to rule out any incorrect calculations */ function _addMCRData( uint len, uint64 newMCRDate, bytes4[] memory curr, uint mcrE, uint mcrP, uint vF, uint[] memory _threeDayAvg ) internal { uint vtp = 0; uint lowerThreshold = 0; uint upperThreshold = 0; if (len > 1) { (vtp, ) = _calVtpAndMCRtp(address(p1).balance); (lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap()); } if(mcrP > dynamicMincapThresholdx100) variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000); // Explanation for above formula :- // actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100 // Implemented formula is simplified form of actual formula. // Let consider above formula as b = b + (a+b)*c/100 // here, dynamicMincapIncrement is in x100 format. // so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000. // It can further simplify to (b.(10000+cx100) + a.cx100)/10000. if (len == 1 || (mcrP) >= lowerThreshold && (mcrP) <= upperThreshold) { vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable pd.pushMCRData(mcrP, mcrE, vF, newMCRDate); for (uint i = 0; i < curr.length; i++) { pd.updateCAAvgRate(curr[i], _threeDayAvg[i]); } emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF); // Oraclize call for next MCR calculation if (vtp < newMCRDate) { _callOracliseForMCR(); } } else { p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime()); } } } // File: nexusmutual-contracts/contracts/Claims.sol /* Copyright (C) 2017 NexusMutual.io 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.5.7; contract Claims is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; NXMToken internal tk; TokenController internal tc; ClaimsReward internal cr; Pool1 internal p1; ClaimsData internal cd; TokenData internal td; PoolData internal pd; Pool2 internal p2; QuotationData internal qd; MCR internal m1; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Gets claim details of claim id = pending claim start + given index */ function getClaimFromNewStart( uint index ) external view returns ( uint coverId, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { (coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender); // status = rewardStatus[statusnumber].claimStatusDesc; } /** * @dev Gets details of a claim submitted by the calling user, at a given index */ function getUserClaimByIndex( uint index ) external view returns( uint status, uint coverId, uint claimId ) { uint statusno; (statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender); status = statusno; } /** * @dev Gets details of a given claim id. * @param _claimId Claim Id. * @return status Current status of claim id * @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial * @return claimOwner Address through which claim is submitted * @return coverId Coverid associated with the claim id */ function getClaimbyIndex(uint _claimId) external view returns ( uint claimId, uint status, int8 finalVerdict, address claimOwner, uint coverId ) { uint stat; claimId = _claimId; (, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId); claimOwner = qd.getCoverMemberAddress(coverId); status = stat; } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns(uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function changePendingClaimStart() public onlyInternal { uint origstat; uint state12Count; uint pendingClaimStart = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = pendingClaimStart; i < actualClaimLength; i++) { (, , , origstat, , state12Count) = cd.getClaim(i); if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60))) cd.setpendingClaimStart(i); else break; } } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) public { address qadd = qd.getCoverMemberAddress(coverId); require(qadd == msg.sender); uint8 cStatus; (, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId); require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted"); require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired"); if (ms.isPause() == false) { _addClaim(coverId, now, qadd); } else { cd.setClaimAtEmergencyPause(coverId, now, false); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested)); } } /** * @dev Submits the Claims queued once the emergency pause is switched off. */ function submitClaimAfterEPOff() public onlyInternal { uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP(); uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP(); uint coverId; uint dateUpd; bool submit; address qadd; for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) { (coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i); require(submit == false); qadd = qd.getCoverMemberAddress(coverId); _addClaim(coverId, dateUpd, qadd); cd.setClaimSubmittedAtEPTrue(i, true); } cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP); } /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Pause Voting of All Pending Claims when Emergency Pause Start. */ function pauseAllPendingClaimsVoting() public onlyInternal { uint firstIndex = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = firstIndex; i < actualClaimLength; i++) { if (checkVoteClosing(i) == 0) { uint dateUpd = cd.getClaimDateUpd(i); cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false); } } } /** * @dev Resume the voting phase of all Claims paused due to an emergency pause. */ function startAllPendingClaimsVoting() public onlyInternal { uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP(); uint i; uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause(); for (i = firstIndx; i < lengthOfClaimVotingPause; i++) { uint pendingTime; uint claimID; (claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i); uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime); cd.setClaimdateUpd(claimID, pTime); cd.setPendingClaimVoteStatus(i, true); uint coverid; (, coverid) = cd.getClaimCoverId(claimID); address qadd = qd.getCoverMemberAddress(coverid); tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime())); p1.closeClaimsOraclise(claimID, uint64(pTime)); } cd.setFirstClaimIndexToStartVotingAfterEP(i); } /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns(int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = -1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } uint time = now; cd.setClaimdateUpd(claimId, time); if (stat >= 2 && stat <= 5) { p1.closeClaimsOraclise(claimId, cd.maxVotingTime()); } if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) { p1.closeClaimsOraclise(claimId, cd.payoutRetryTime()); } else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) { uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now)); p1.closeClaimsOraclise(claimId, timeLeft); } } /** * @dev Submits a claim for a given cover note. * Set deposits flag against cover. */ function _addClaim(uint coverId, uint time, address add) internal { tf.depositCN(coverId); uint len = cd.actualClaimLength(); cd.addClaim(len, coverId, add, now); cd.callClaimEvent(coverId, add, len, time); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); bytes4 curr = qd.getCurrencyOfCover(coverId); uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured)); p2.internalLiquiditySwap(curr); p1.closeClaimsOraclise(len, cd.maxVotingTime()); } } // File: nexusmutual-contracts/contracts/ClaimsReward.sol /* Copyright (C) 2020 NexusMutual.io 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/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity 0.5.7; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool1 internal p1; Pool2 internal p2; PoolData internal pd; Governance internal gv; IPooledStaking internal pooledStaking; uint private constant DECIMAL1E18 = uint(10) ** 18; function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { uint coverid; (, coverid) = cd.getClaimCoverId(claimid); uint status; (, status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) { // when current status is "Claim Accepted Payout Pending" uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); address payable coverHolder = qd.getCoverMemberAddress(coverid); bytes4 coverCurrency = qd.getCurrencyOfCover(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency); if (success) { tf.burnStakedTokens(coverid, coverCurrency, sumAssured); c1.setClaimStatus(claimid, 14); } } c1.changePendingClaimStart(); } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenCA(claimId); } else { (, , totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenMV(claimId); }else { (, , totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns(uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } (reward, , , ) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns(uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); bytes4 curr = qd.getCurrencyOfCover(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); td.setDepositCN(coverid, false); // Unset flag tf.burnDepositCN(coverid); // burn Deposited CN pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured)); p2.internalLiquiditySwap(curr); } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); td.setDepositCN(coverid, false); // Unset flag tf.unlockCN(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr); if (success) { tf.burnStakedTokens(coverid, curr, sumAssured); } } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, -1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, -1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex, ) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc, , ) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total=0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); //solhint-disable-line } } // File: nexusmutual-contracts/contracts/MemberRoles.sol /* Copyright (C) 2017 GovBlocks.io 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.5.7; contract MemberRoles is IMemberRoles, Governed, Iupgradable { TokenController public dAppToken; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember ( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner ( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); dAppToken = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate (address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole( //solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole( //solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i=0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); dAppToken.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); dAppToken.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); //solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); //solhint-disable-line } } /** * @dev Called by existed member if wish to Withdraw membership. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist } /** * @dev Called by existed member if wish to switch membership to other address. * @param _add address of user to forward membership. */ function switchMembership(address _add) external { require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.addToWhitelist(_add); _updateRole(_add, uint(Role.Member), true); tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); emit switchedMembership(msg.sender, _add, now); } /// @dev Return number of member roles function totalRoles() public view returns(uint256) { //solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns(bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } // File: nexusmutual-contracts/contracts/ProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io 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.5.7; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping (uint => CategoryAction) internal categoryActionData; mapping (uint => uint) public categoryABReq; mapping (uint => uint) public isSpecialResolution; mapping (uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Restricts calls to deprecated functions */ modifier deprecated() { revert("Function deprecated"); _; } /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external deprecated { } /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external deprecated { //solhint-disable-line } /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns(uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) { return( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) { return( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public deprecated { } /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns(uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io 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.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Initiates add solution /// @param _solutionHash Solution hash having required data against adding solution function addSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Opens proposal for voting function openProposalForVoting(uint _proposalId) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function pauseProposal(uint _proposalId) public; function resumeProposal(uint _proposalId) public; function allowedToCatgorize() public view returns(uint roleId); } // File: nexusmutual-contracts/contracts/Governance.sol // /* Copyright (C) 2017 GovBlocks.io // 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.5.7; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint=>uint) memberVoteValue; mapping(uint=>uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping (address => mapping(uint => uint)) public memberProposalVote; mapping (address => uint) public followerDelegation; mapping (address => uint) internal followerCount; mapping (address => uint[]) internal leaderDelegation; mapping (uint => VoteTally) public proposalVoteTally; mapping (address => bool) public isOpenForDelegation; mapping (address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Initiates add solution * To implement the governance interface */ function addSolution(uint, string calldata, bytes calldata) external { } /** * @dev Opens proposal for voting * To implement the governance interface */ function openProposalForVoting(uint) external { } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) { return( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns(uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns(uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns(bool check) { if (category == 0) return true; uint[] memory mrAllowed; (, , , , mrAllowed, , ) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns(bool delegated) { for (uint i=0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Pauses a proposal * To implement govblocks interface */ function pauseProposal(uint) public { } /** * @dev Resumes a proposal * To implement govblocks interface */ function resumeProposal(uint) public { } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns(uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns(uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime, ) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10**18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10**18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns(uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns(bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } (bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (, , majorityVote, , , , ) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (, , _majorityVote, , , , ) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } }
Change Dependent Contract Address/
function changeDependentContractAddress() public { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); }
7,286,597
/** * @title Toft Standard Token (TST) * Version: 1.0 */ pragma solidity 0.5.0; 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]; } } 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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); } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } 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); } } contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract ERC20 is 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")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: 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; } } contract ERC20Burnable is 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); } } contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } interface ITST { /** * @dev sets existing feeAccount to `feeAccount` by the caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {FeeAccountUpdated} event indicating the new FeeAccount. */ function setFeeAccount(address feeAccount) external returns (bool); /** * @dev sets existing maxTransferFee to `_maxTransferFee` by the caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {MaxTransferFeeUpdated} event indicating the new maximum transfer fee. */ function setMaxTransferFee(uint256 maxTransferFee) external returns (bool); /** * @dev sets existing minTransferFee to `_minTransferFee` by the caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {MinTransferFeeUpdated} event indicating the new minimum transfer fee. */ function setMinTransferFee(uint256 minTransferFee) external returns (bool); /** * @dev sets existing transferFeePercentage to `_transferFeePercentage` by the caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {TransferFeePercentageUpdated} event indicating the new percentange transfer fee. */ function setTransferFeePercentage(uint256 transferFeePercentage) external returns (bool); /** * @dev calculate transfer fee aginst `weiAmount`. * @param weiAmount Value in wei to be to calculate fee. * @return Number of tokens in wei to paid for transfer fee. */ function calculateTransferFee(uint256 weiAmount) external view returns(uint256) ; /** * @return the current fee account collector. */ function feeAccount() external view returns (address); /** * @return the current maximum transfer fee. */ function maxTransferFee() external view returns (uint256); /** * @return the current minimum transfer fee. */ function minTransferFee() external view returns (uint256); /** * @return the current percentange of transfer fee. */ function transferFeePercentage() external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient` with a transaction note `message`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount, string calldata message) external returns (bool); /** * Event for FeeAccount update. * @param newFeeAccount new FeeAccount. * @param previousFeeAccount old FeeAccount. */ event FeeAccountUpdated(address indexed previousFeeAccount, address indexed newFeeAccount); /** * Event for MaxTransferFee update. * @param newMaxTransferFee new maximum tranfer fee. * @param previousMaxTransferFee old maximum tranfer fee. */ event MaxTransferFeeUpdated(uint256 previousMaxTransferFee, uint256 newMaxTransferFee); /** * Event for MinTransferFee update. * @param newMinTransferFee new minimum tranfer fee. * @param previousMinTransferFee old minimum tranfer fee. */ event MinTransferFeeUpdated(uint256 previousMinTransferFee, uint256 newMinTransferFee); /** * Event for TransferFeePercentage update. * @param newTransferFeePercentage new percentange tranfer fee. * @param previousTransferFeePercentage old percentange tranfer fee. */ event TransferFeePercentageUpdated(uint256 previousTransferFeePercentage, uint256 newTransferFeePercentage); /** * @dev emitted with token transfer is done. * @param from the account from which tokens are moved. * @param to the recipient of tokens. * @param value the amount to tokens moved. * @param fee the account to fee deducted from `from`. */ event Transfer(address indexed from, address indexed to, uint256 value, uint256 fee, string description); } /* * TransferFee * Base contract for trasfer fee specification. */ contract TransferFee is Ownable, ITST { address private _feeAccount; uint256 private _maxTransferFee; uint256 private _minTransferFee; uint256 private _transferFeePercentage; /** * @dev Constructor, _feeAccount that collects tranfer fee, fee percentange, maximum, minimum amount of wei for trasfer fee. * @param feeAccount account that collects fee. * @param minTransferFee Min amount of wei to be charged on trasfer. * @param minTransferFee Min amount of wei to be charged on trasfer. * @param transferFeePercentage Percent amount of wei to be charged on trasfer. */ constructor (address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage) public { require(feeAccount != address(0x0), "TransferFee: feeAccount is 0"); require(minTransferFee > 0, "TransferFee: minTransferFee is 0"); require(maxTransferFee > 0, "TransferFee: maxTransferFee is 0"); require(transferFeePercentage > 0, "TransferFee: transferFeePercentage is 0"); // this also handles "minTransferFee should be less than maxTransferFee" // solhint-disable-next-line max-line-length require(maxTransferFee > minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee"); _feeAccount = feeAccount; _maxTransferFee = maxTransferFee; _minTransferFee = minTransferFee; _transferFeePercentage = transferFeePercentage; } /** * See {ITrasnferFee-setFeeAccount}. * * @dev sets `feeAccount` to `_feeAccount` by the caller. * * Requirements: * * - `feeAccount` cannot be the zero. */ function setFeeAccount(address feeAccount) external onlyOwner returns (bool) { require(feeAccount != address(0x0), "TransferFee: feeAccount is 0"); emit FeeAccountUpdated(_feeAccount, feeAccount); _feeAccount = feeAccount; return true; } /** * See {ITrasnferFee-setMaxTransferFee}. * * @dev sets `maxTransferFee` to `_maxTransferFee` by the caller. * * Requirements: * * - `maxTransferFee` cannot be the zero. * - `maxTransferFee` should be greater than minTransferFee. */ function setMaxTransferFee(uint256 maxTransferFee) external onlyOwner returns (bool) { require(maxTransferFee > 0, "TransferFee: maxTransferFee is 0"); // solhint-disable-next-line max-line-length require(maxTransferFee > _minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee"); emit MaxTransferFeeUpdated(_maxTransferFee, maxTransferFee); _maxTransferFee = maxTransferFee; return true; } /** * See {ITrasnferFee-setMinTransferFee}. * * @dev sets `minTransferFee` to `_minTransferFee` by the caller. * * Requirements: * * - `minTransferFee` cannot be the zero. * - `minTransferFee` should be less than maxTransferFee. */ function setMinTransferFee(uint256 minTransferFee) external onlyOwner returns (bool) { require(minTransferFee > 0, "TransferFee: minTransferFee is 0"); // solhint-disable-next-line max-line-length require(minTransferFee < _maxTransferFee, "TransferFee: minTransferFee should be less than maxTransferFee"); emit MaxTransferFeeUpdated(_minTransferFee, minTransferFee); _minTransferFee = minTransferFee; return true; } /** * See {ITrasnferFee-setTransferFeePercentage}. * * @dev sets `transferFeePercentage` to `_transferFeePercentage` by the caller. * * Requirements: * * - `transferFeePercentage` cannot be the zero. * - `transferFeePercentage` should be less than maxTransferFee. */ function setTransferFeePercentage(uint256 transferFeePercentage) external onlyOwner returns (bool) { require(transferFeePercentage > 0, "TransferFee: transferFeePercentage is 0"); emit TransferFeePercentageUpdated(_transferFeePercentage, transferFeePercentage); _transferFeePercentage = transferFeePercentage; return true; } /** * @dev See {ITrasnferFee-feeAccount}. */ function feeAccount() public view returns (address) { return _feeAccount; } /** * See {ITrasnferFee-maxTransferFee}. */ function maxTransferFee() public view returns (uint256) { return _maxTransferFee; } /** * See {ITrasnferFee-minTransferFee}. */ function minTransferFee() public view returns (uint256) { return _minTransferFee; } /** * See {ITrasnferFee-transferFeePercentage}. */ function transferFeePercentage() public view returns (uint256) { return _transferFeePercentage; } } /** * @title Toft Standard Token * @dev TST implementation. */ contract TST is Context, Ownable, ERC20, ERC20Detailed, ERC20Burnable, ERC20Mintable, ERC20Pausable, TransferFee { // TOFT: EVENTS ADDED TO MAKE THIS CONTRACT COMPATIBLE WITH EXISTING APPS /** * @dev emitted with token transfer is done. * @param from the account from which tokens are moved. * @param to the recipient of tokens. * @param value the amount to tokens moved. * @param fee the account to fee deducted from `from`. * @param description a message for token transfer. * @param timestamp current block timestamp. */ event Transfer(address indexed from, address indexed to, uint256 value, uint256 fee, string description, uint256 timestamp); /** * @dev Constructor that gives _msgSender() all of existing tokens. */ constructor (string memory name, string memory symbol, uint8 decimals, address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint8 transferFeePercentage) public ERC20Detailed(name, symbol, decimals) TransferFee(feeAccount, maxTransferFee, minTransferFee, transferFeePercentage) { _mint(_msgSender(), 0); } /** * @dev calculate transfer fee aginst `weiAmount`. * @param weiAmount Value in wei to be to calculate fee. * @return Number of tokens in wei to paid for transfer fee. */ function calculateTransferFee(uint256 weiAmount) public view returns(uint256) { uint256 divisor = uint256(100).mul((10**uint256(decimals()))); uint256 _fee = (transferFeePercentage().mul(weiAmount)).div(divisor); if (_fee < minTransferFee()) { _fee = minTransferFee(); } else if (_fee > maxTransferFee()) { _fee = maxTransferFee(); } return _fee; } /** * @dev override IERC20-transfer to deducted transfer fee from `amount` * @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) { require(recipient != address(this), "ERC20: transfer to the this contract"); uint256 _fee = calculateTransferFee(amount); uint256 _amount = amount.sub(_fee); // calling ERC20 transfer function to transfer tokens super.transfer(recipient, _amount); // TST super.transfer(feeAccount(), _fee); // transfering fee to fee account emit Transfer(msg.sender, recipient, _amount, _fee, "", now); return true; } /** * @dev overriding version of ${transfer} that includes message in token transfer * */ function transfer(address recipient, uint256 amount, string calldata message) external returns (bool) { require(recipient != address(this), "ERC20: transfer to the this contract"); uint256 _fee = calculateTransferFee(amount); uint256 _amount = amount.sub(_fee); // calling ERC20 transfer function to transfer tokens super.transfer(recipient, _amount); // TST super.transfer(feeAccount(), _fee); // transfering fee to fee account emit Transfer(msg.sender, recipient, _amount, _fee, message); return true; } /** * @dev Called by a pauser to unpause. * this function is override from ERC20Pausable to keep contract in paused state */ function unpause() public onlyPauser whenPaused { require(false, "contract can't be unpaused"); } /** * @dev overloading burn function to enable token burn from any account * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(address account, uint256 amount) public onlyOwner { _burn(account, amount); } /** * @dev overridding mint function to enable token minting to only owner address. * @dev Mints `amount` tokens to the owner address. * * See {ERC20Mintable-mint}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { require(account == owner(), "mint: tokens can be only minted on owner address"); _mint(account, amount); return true; } /** * @dev See {IERC20-totalSupply}. * @return the current supply of tokens. * * Requirements: * * - the caller must have the {Owner}. */ function totalSupply() public view onlyOwner returns (uint256) { return super.totalSupply(); } // TOFT: THESE FUNCTIONS ARE ADDED TO MAKE THIS CONTRACT COMPATIBLE WITH EXISTING APPS /** * @dev legacy sendFunds function to make contract compatible with existing applications * * @param from the sender of tokens * @param to the recipient of tokens. * @param value the amount to tokens moved. * @param description a message for token transfer. */ function sendFunds(address from, address to, uint256 value, string memory description) public { require(to != address(this), "ERC20: transfer to the this contract"); uint256 _fee = calculateTransferFee(value); uint256 _amount = value.sub(_fee); // calling ERC20 transfer function to transfer tokens super.transfer(to, _amount); // TST super.transfer(feeAccount(), _fee); // transfering fee to fee account emit Transfer(from, to, _amount, _fee, description, now); } function increaseSupply(address target, uint256 amount) public { mint(target,amount); } function decreaseSupply(address target, uint256 amount) public { burn(target,amount); } function getOwner() public view returns (address) { return owner(); } function getName() public view returns (string memory) { return name(); } function getFeeAccount() public view returns (address) { return feeAccount(); } function getTotalSupply() public view returns (uint256) { return totalSupply(); } function getMaxTransferFee() public view returns (uint256) { return maxTransferFee(); } function getMinTransferFee() public view returns (uint256) { return minTransferFee(); } function getTransferFeePercentage() public view returns (uint256) { return transferFeePercentage(); } function getBalance(address balanceAddress) public view returns (uint256) { return balanceOf(balanceAddress); } }
overloading burn function to enable token burn from any account Destroys `amount` tokens from the caller. See {ERC20-_burn}./
function burn(address account, uint256 amount) public onlyOwner { _burn(account, amount); }
12,662,987
./partial_match/1/0x923b533364E96C64A481698a3B7E5983d16f17Aa/sources/packages/contracts/src/TheGardenNFT.sol
Mark a specific token id as collected by an operator contract Reverts if: - `id` has already been collected - `id` is not a token from the current `activeBatch` - caller is not approved for the current `activeBatch` id The token id that was collected/ Mark the token as collected
function markAsCollected(uint256 id) public override onlyWhenTokenIsInActiveBatch(id) onlyWhenOperatorForActiveBatch nonReentrant { _collectToken(id); } ------------------------------------------------------------------------ */
16,029,212
/// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; import "Ownable.sol"; import "ISheetFighterToken.sol"; import "ICellToken.sol"; import "IPortal.sol"; /// @title Contract to send Sheet Fighters and $CELL between Ethereum and Polygon /// @author Overlord Paper Co. /// @notice A big thank you to 0xBasset from EtherOrcs! This contract is heavily influenced /// @notice by the the EtherOrcs Ethereum <--> Polygon bridge, and 0xBasset was a great /// @notice sounding board during development. contract Scanner is Ownable { address public portal; address public sheetFighterToken; address public cellToken; mapping (address => address) public reflection; mapping (uint256 => address) public sheetOwner; constructor() Ownable() {} modifier onlyPortal() { require(portal != address(0), "Portal must be set"); require(msg.sender == portal, "Only portal can do this"); _; } /// @dev Initiatilize state for proxy contract /// @param portal_ Portal address /// @param sheetFighterToken_ SheetFighterToken address /// @param cellToken_ CellToken address function initialize( address portal_, address sheetFighterToken_, address cellToken_ ) external onlyOwner { portal = portal_; sheetFighterToken = sheetFighterToken_; cellToken = cellToken_; } /// @dev Set Ethereum <--> Polygon reflection address /// @param key_ Address for contract on one network /// @param reflection_ Address for contract on sister network function setReflection(address key_, address reflection_) external onlyOwner { reflection[key_] = reflection_; reflection[reflection_] = key_; } /// @notice Bridge your Sheet Fighter(s) and $CELL between Ethereum and Polygon /// @notice This contract must be approved to transfer your Sheet Fighter(s) on your behalf /// @notice Sheet Fighter(s) must be in your wallet (i.e. not staked or bridged) to travel /// @param sheetFighterIds Ids of the Sheet Fighters being bridged /// @param cellAmount Amount of $CELL to bridge function travel(uint256[] calldata sheetFighterIds, uint256 cellAmount) external { require(sheetFighterIds.length > 0 || cellAmount > 0, "Can't bridge nothing"); // Address of contract on the sister-chain address target = reflection[address(this)]; uint256 numSheetFighters = sheetFighterIds.length; uint256 currIndex = 0; bytes[] memory calls = new bytes[]((numSheetFighters > 0 ? numSheetFighters + 1 : 0) + (cellAmount > 0 ? 1 : 0)); // Handle Sheets if(numSheetFighters > 0 ) { // Transfer Sheets to bridge (SheetFighterToken contract then calls callback on this contract) _pullIds(sheetFighterToken, sheetFighterIds); // Recreate Sheets on sister-chain exact as they exist on this chain for(uint256 i = 0; i < numSheetFighters; i++) { calls[i] = _buildData(sheetFighterIds[i]); } calls[numSheetFighters] = abi.encodeWithSelector(this.unstakeMany.selector, reflection[sheetFighterToken], msg.sender, sheetFighterIds); currIndex += numSheetFighters + 1; } // Handle $CELL if(cellAmount > 0) { // Burn $CELL on this side of bridge ICellToken(cellToken).bridgeBurn(msg.sender, cellAmount); // Add call to mint $CELL on other side of bridge calls[currIndex] = abi.encodeWithSelector(this.mintCell.selector, reflection[cellToken], msg.sender, cellAmount); } // Send messages to portal IPortal(portal).sendMessage(abi.encode(target, calls)); } /// @dev Callback function called by SheetFighterToken contract during travel /// @dev "Stakes" all Sheets being bridged to this contract (i.e. transfers custody to this contract) /// @param owner Address of the owner of the Sheet Fighters being bridged /// @param tokenIds Token ids of the Sheet Fighters being bridged function bridgeTokensCallback(address owner, uint256[] calldata tokenIds) external { require(msg.sender == sheetFighterToken, "Only SheetFighterToken contract can do this"); for(uint256 i = 0; i < tokenIds.length; i++) { _stake(msg.sender, tokenIds[i], owner); } } /// @dev Unstake the Sheet Fighters from this contract and transfer ownership to owner /// @dev Called on the "to" network for bridging /// @param token Address of the ERC721 contract fot the tokens being bridged /// @param owner Address of the owner of the Sheet Fighters being bridged /// @param ids ERC721 token ids of the Sheet Fighters being bridged function unstakeMany(address token, address owner, uint256[] calldata ids) external onlyPortal { for (uint256 i = 0; i < ids.length; i++) { delete sheetOwner[ids[i]]; IERC721(token).transferFrom(address(this), owner, ids[i]); } } /// @dev Calls the SheetFighterToken contract with given calldata /// @dev This is used to execute the cross-chain function calls /// @param data Calldata with which to call SheetFighterToken function callSheets(bytes calldata data) external onlyPortal { (bool succ, ) = sheetFighterToken.call(data); require(succ); } /// @dev Mint $CELL on the "to" network /// @param token Address of CellToken contract /// @param to Address of user briding $CELL /// @param amount Amount of $CELL being bridged function mintCell(address token, address to, uint256 amount) external onlyPortal { ICellToken(token).bridgeMint(to, amount); } /// @dev Informs other contracts that this contract knows about ERC721s /// @dev Allows ERC721 safeTransfer and safeTransferFrom transactions to this contract function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure returns (bytes4) { return this.onERC721Received.selector; } /// @dev Call the bridgeSheets function on the "from" part of the network, which transfers tokens /// @param tokenAddress Address of SheetFighterToken contract /// @param tokenIds SheetFighterToken ids of Sheet Fighters being bridged function _pullIds(address tokenAddress, uint256[] calldata tokenIds) internal { // The ownership will be checked to the token contract ISheetFighterToken(tokenAddress).bridgeSheets(msg.sender, tokenIds); } /// @dev Set state variables mapping tokenId to owner /// @param token Address of ERC721 contract /// @param tokenId ERC721 id for token being staked /// @param owner Address of owner who is bridging function _stake(address token, uint256 tokenId, address owner) internal { require(sheetOwner[tokenId] == address(0), "Token already staked"); require(msg.sender == token, "Not SF contract"); require(IERC721(token).ownerOf(tokenId) == address(this), "Sheet not transferred"); if (token == sheetFighterToken){ sheetOwner[tokenId] = owner; } } /// @dev build calldata for transaction to update Sheet's stats /// @param id SheetFighterToken id function _buildData(uint256 id) internal view returns (bytes memory) { (uint8 hp, uint8 critical, uint8 heal, uint8 defense, uint8 attack, , ) = ISheetFighterToken(sheetFighterToken).tokenStats(id); bytes memory data = abi.encodeWithSelector(this.callSheets.selector, abi.encodeWithSelector(ISheetFighterToken.syncBridgedSheet.selector, id, hp, critical, heal, defense, attack)); return data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721Enumerable.sol"; interface ISheetFighterToken is IERC721Enumerable { /// @notice Update the address of the CellToken contract /// @param _contractAddress Address of the CellToken contract function setCellTokenAddress(address _contractAddress) external; /// @notice Update the address which signs the mint transactions /// @dev Used for ensuring GPT-3 values have not been altered /// @param _mintSigner New address for the mintSigner function setMintSigner(address _mintSigner) external; /// @notice Update the address of the bridge /// @dev Used for authorization /// @param _bridge New address for the bridge function setBridge(address _bridge) external; /// @notice Update the address of the upgrade contract /// @dev Used for authorization /// @param _upgradeContract New address for the upgrade contract function setUpgradeContract(address _upgradeContract) external; /// @dev Withdraw funds as owner function withdraw() external; /// @notice Set the sale state: options are 0 (closed), 1 (presale), 2 (public sale) -- only owner can call /// @dev Implicitly converts int argument to TokenSaleState type -- only owner can call /// @param saleStateId The id for the sale state: 0 (closed), 1 (presale), 2 (public sale) function setSaleState(uint256 saleStateId) external; /// @notice Mint up to 20 Sheet Fighters /// @param numTokens Number of Sheet Fighter tokens to mint (1 to 20) function mint(uint256 numTokens) external payable; /// @notice "Print" a Sheet. Adds GPT-3 flavor text and attributes /// @dev This function requires signature verification /// @param _tokenIds Array of tokenIds to print /// @param _flavorTexts Array of strings with flavor texts concatonated with a pipe character /// @param _signature Signature verifying _flavorTexts are unmodified function print( uint256[] memory _tokenIds, string[] memory _flavorTexts, bytes memory _signature ) external; /// @notice Bridge the Sheets /// @dev Transfers Sheets to bridge /// @param tokenOwner Address of the tokenOwner who is bridging their tokens /// @param tokenIds Array of tokenIds that tokenOwner is bridging function bridgeSheets(address tokenOwner, uint256[] calldata tokenIds) external; /// @notice Update the sheet to sync with actions that occured on otherside of bridge /// @param tokenId Id of the SheetFighter /// @param HP New HP value /// @param critical New luck value /// @param heal New heal value /// @param defense New defense value /// @param attack New attack value function syncBridgedSheet( uint256 tokenId, uint8 HP, uint8 critical, uint8 heal, uint8 defense, uint8 attack ) external; /// @notice Get Sheet stats /// @param _tokenId Id of SheetFighter /// @return tuple containing sheet's stats function tokenStats(uint256 _tokenId) external view returns(uint8, uint8, uint8, uint8, uint8, uint8, uint8); /// @notice Return true if token is printed, false otherwise /// @param _tokenId Id of the SheetFighter NFT /// @return bool indicating whether or not sheet is printed function isPrinted(uint256 _tokenId) external view returns(bool); /// @notice Returns the token metadata and SVG artwork /// @dev This generates a data URI, which contains the metadata json, encoded in base64 /// @param _tokenId The tokenId of the token whos metadata and SVG we want function tokenURI(uint256 _tokenId) external view returns (string memory); /// @notice Update the sheet to via upgrade contract /// @param tokenId Id of the SheetFighter /// @param attributeNumber specific attribute to upgrade /// @param value new attribute value function updateStats(uint256 tokenId,uint8 attributeNumber,uint8 value) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC20.sol"; /// @title Contract creating fungible in-game utility tokens for the Sheet Fighter game /// @author Overlord Paper Co /// @notice This defines in-game utility tokens that are used for the Sheet Fighter game /// @notice This contract is HIGHLY adapted from the Anonymice $CHEETH contract /// @notice Thank you MouseDev for writing the original $CHEETH contract! interface ICellToken is IERC20 { /// @notice Update the address of the SheetFighterToken contract /// @param _contractAddress Address of the SheetFighterToken contract function setSheetFighterTokenAddress(address _contractAddress) external; /// @notice Update the address of the bridge /// @dev Used for authorization /// @param _bridge New address for the bridge function setBridge(address _bridge) external; /// @notice Stake multiple Sheets by providing their Ids /// @param tokenIds Array of SheetFighterToken ids to stake function stakeByIds(uint256[] calldata tokenIds) external; /// @notice Unstake all of your SheetFighterTokens and get your rewards /// @notice This function is more gas efficient than calling unstakeByIds(...) for all ids /// @dev Tokens are iterated over in REVERSE order, due to the implementation of _remove(...) function unstakeAll() external; /// @notice Unstake SheetFighterTokens, given by ids, and get your rewards /// @notice Use unstakeAll(...) instead if unstaking all tokens for gas efficiency /// @param tokenIds Array of SheetFighterToken ids to unstake function unstakeByIds(uint256[] memory tokenIds) external; /// @notice Claim $CELL tokens as reward for staking a SheetFighterTokens, given by an id /// @notice This function does not unstake your Sheets /// @param tokenId SheetFighterToken id function claimByTokenId(uint256 tokenId) external; /// @notice Claim $CELL tokens as reward for all SheetFighterTokens staked /// @notice This function does not unstake your Sheets function claimAll() external; /// @notice Mint tokens when bridging /// @dev This function is only used for bridging to mint tokens on one end /// @param to Address to send new tokens to /// @param value Number of new tokens to mint function bridgeMint(address to, uint256 value) external; /// @notice Burn tokens when bridging /// @dev This function is only used for bridging to burn tokens on one end /// @param from Address to burn tokens from /// @param value Number of tokens to burn function bridgeBurn(address from, uint256 value) external; /// @notice View all rewards claimable by a staker /// @param staker Address of the staker /// @return Number of $CELL claimable by the staker function getAllRewards(address staker) external view returns (uint256); /// @notice View rewards claimable for a specific SheetFighterToken /// @param tokenId Id of the SheetFightToken /// @return Number of $CELL claimable by the staker for this Sheet function getRewardsByTokenId(uint256 tokenId) external view returns (uint256); /// @notice Get all the token Ids staked by a staker /// @param staker Address of the staker /// @return Array of tokens staked function getTokensStaked(address staker) external view returns (uint256[] memory); /// @notice Burn cell on behalf of an account /// @param account Address for account /// @param amount Amount to burn function burnFrom(address account, uint256 amount) external; } // 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; interface IPortal { function sendMessage(bytes calldata message_) external; function processMessageFromRoot(uint256 stateId, address rootMessageSender, bytes calldata data) external; function receiveMessage(bytes memory data) external; }
Bridge your Sheet Fighter(s) and $CELL between Ethereum and Polygon This contract must be approved to transfer your Sheet Fighter(s) on your behalf Sheet Fighter(s) must be in your wallet (i.e. not staked or bridged) to travel sheetFighterIds Ids of the Sheet Fighters being bridged cellAmount Amount of $CELL to bridge Address of contract on the sister-chain Handle Sheets Transfer Sheets to bridge (SheetFighterToken contract then calls callback on this contract) Recreate Sheets on sister-chain exact as they exist on this chain Handle $CELL Burn $CELL on this side of bridge Add call to mint $CELL on other side of bridge
function travel(uint256[] calldata sheetFighterIds, uint256 cellAmount) external { require(sheetFighterIds.length > 0 || cellAmount > 0, "Can't bridge nothing"); address target = reflection[address(this)]; uint256 numSheetFighters = sheetFighterIds.length; uint256 currIndex = 0; bytes[] memory calls = new bytes[]((numSheetFighters > 0 ? numSheetFighters + 1 : 0) + (cellAmount > 0 ? 1 : 0)); if(numSheetFighters > 0 ) { _pullIds(sheetFighterToken, sheetFighterIds); for(uint256 i = 0; i < numSheetFighters; i++) { calls[i] = _buildData(sheetFighterIds[i]); } calls[numSheetFighters] = abi.encodeWithSelector(this.unstakeMany.selector, reflection[sheetFighterToken], msg.sender, sheetFighterIds); currIndex += numSheetFighters + 1; } if(cellAmount > 0) { ICellToken(cellToken).bridgeBurn(msg.sender, cellAmount); calls[currIndex] = abi.encodeWithSelector(this.mintCell.selector, reflection[cellToken], msg.sender, cellAmount); } }
11,829,044
./full_match/9001/0xCE3CA8DE98865bCCb18B893B6e3952722a401360/sources/contracts/StarFarm.sol
@error Exception to be handled
interface INFTLogic { function starMeta(uint256 _tokenId) view external returns (uint8, uint256, uint256, uint256); }
11,534,618
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/ISushiStake.sol"; import "./libs/IWETH.sol"; import "./BaseStrategyLP.sol"; contract StrategyMasterchefDouble is BaseStrategyLP { using SafeMath for uint256; using SafeERC20 for IERC20; address public masterchefAddress; uint256 public pid; address public constant wmaticAddress = 0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270; address[] public wmaticToUsdcPath; address[] public wmaticToFishPath; address[] public wmaticToToken0Path; address[] public wmaticToToken1Path; constructor( address _masterchefAddress, address _uniRouterAddress, uint256 _pid, address _wantAddress, address _earnedAddress, address[] memory _earnedToWmaticPath, address[] memory _earnedToUsdcPath, address[] memory _earnedToFishPath, address[] memory _wmaticToUsdcPath, address[] memory _wmaticToFishPath, address[] memory _earnedToToken0Path, address[] memory _earnedToToken1Path, address[] memory _wmaticToToken0Path, address[] memory _wmaticToToken1Path, address[] memory _token0ToEarnedPath, address[] memory _token1ToEarnedPath ) public { govAddress = msg.sender; vaultChefAddress = 0xBdA1f897E851c7EF22CD490D2Cf2DAce4645A904; // Stack too deep masterchefAddress = _masterchefAddress; uniRouterAddress = _uniRouterAddress; wantAddress = _wantAddress; token0Address = IUniPair(wantAddress).token0(); token1Address = IUniPair(wantAddress).token1(); pid = _pid; earnedAddress = _earnedAddress; earnedToWmaticPath = _earnedToWmaticPath; earnedToUsdcPath = _earnedToUsdcPath; earnedToFishPath = _earnedToFishPath; wmaticToUsdcPath = _wmaticToUsdcPath; wmaticToFishPath = _wmaticToFishPath; earnedToToken0Path = _earnedToToken0Path; earnedToToken1Path = _earnedToToken1Path; wmaticToToken0Path = _wmaticToToken0Path; wmaticToToken1Path = _wmaticToToken1Path; token0ToEarnedPath = _token0ToEarnedPath; token1ToEarnedPath = _token1ToEarnedPath; transferOwnership(vaultChefAddress); _resetAllowances(); } function _vaultDeposit(uint256 _amount) internal override { ISushiStake(masterchefAddress).deposit(pid, _amount, address(this)); } function _vaultWithdraw(uint256 _amount) internal override { ISushiStake(masterchefAddress).withdraw(pid, _amount, address(this)); } function earn() external override nonReentrant whenNotPaused onlyGov { // Harvest farm tokens ISushiStake(masterchefAddress).harvest(pid, address(this)); // Converts farm tokens into want tokens uint256 earnedAmt = IERC20(earnedAddress).balanceOf(address(this)); uint256 wmaticAmt = IERC20(wmaticAddress).balanceOf(address(this)); if (earnedAmt > 0) { earnedAmt = distributeFees(earnedAmt, earnedAddress); earnedAmt = distributeRewards(earnedAmt, earnedAddress); earnedAmt = buyBack(earnedAmt, earnedAddress); if (earnedAddress != token0Address) { // Swap half earned to token0 _safeSwap( earnedAmt.div(2), earnedToToken0Path, address(this) ); } if (earnedAddress != token1Address) { // Swap half earned to token1 _safeSwap( earnedAmt.div(2), earnedToToken1Path, address(this) ); } } if (wmaticAmt > 0) { wmaticAmt = distributeFees(wmaticAmt, wmaticAddress); wmaticAmt = distributeRewards(wmaticAmt, wmaticAddress); wmaticAmt = buyBack(wmaticAmt, wmaticAddress); if (wmaticAddress != token0Address) { // Swap half earned to token0 _safeSwap( wmaticAmt.div(2), wmaticToToken0Path, address(this) ); } if (wmaticAddress != token1Address) { // Swap half earned to token1 _safeSwap( wmaticAmt.div(2), wmaticToToken1Path, address(this) ); } } if (earnedAmt > 0 || wmaticAmt > 0) { // Get want tokens, ie. add liquidity uint256 token0Amt = IERC20(token0Address).balanceOf(address(this)); uint256 token1Amt = IERC20(token1Address).balanceOf(address(this)); if (token0Amt > 0 && token1Amt > 0) { IUniRouter02(uniRouterAddress).addLiquidity( token0Address, token1Address, token0Amt, token1Amt, 0, 0, address(this), now.add(600) ); } lastEarnBlock = block.number; _farm(); } } // To pay for earn function function distributeFees(uint256 _earnedAmt, address _earnedAddress) internal returns (uint256) { if (controllerFee > 0) { uint256 fee = _earnedAmt.mul(controllerFee).div(feeMax); if (_earnedAddress == wmaticAddress) { IWETH(wmaticAddress).withdraw(fee); safeTransferETH(feeAddress, fee); } else { _safeSwapWmatic( fee, earnedToWmaticPath, feeAddress ); } _earnedAmt = _earnedAmt.sub(fee); } return _earnedAmt; } function distributeRewards(uint256 _earnedAmt, address _earnedAddress) internal returns (uint256) { if (rewardRate > 0) { uint256 fee = _earnedAmt.mul(rewardRate).div(feeMax); uint256 usdcBefore = IERC20(usdcAddress).balanceOf(address(this)); _safeSwap( fee, _earnedAddress == wmaticAddress ? wmaticToUsdcPath : earnedToUsdcPath, address(this) ); uint256 usdcAfter = IERC20(usdcAddress).balanceOf(address(this)).sub(usdcBefore); IStrategyFish(rewardAddress).depositReward(usdcAfter); _earnedAmt = _earnedAmt.sub(fee); } return _earnedAmt; } function buyBack(uint256 _earnedAmt, address _earnedAddress) internal returns (uint256) { if (buyBackRate > 0) { uint256 buyBackAmt = _earnedAmt.mul(buyBackRate).div(feeMax); _safeSwap( buyBackAmt, _earnedAddress == wmaticAddress ? wmaticToFishPath : earnedToFishPath, buyBackAddress ); _earnedAmt = _earnedAmt.sub(buyBackAmt); } return _earnedAmt; } function vaultSharesTotal() public override view returns (uint256) { (uint256 balance,) = ISushiStake(masterchefAddress).userInfo(pid, address(this)); return balance; } function wantLockedTotal() public override view returns (uint256) { (uint256 balance,) = ISushiStake(masterchefAddress).userInfo(pid, address(this)); return IERC20(wantAddress).balanceOf(address(this)).add(balance); } function _resetAllowances() internal override { IERC20(wantAddress).safeApprove(masterchefAddress, uint256(0)); IERC20(wantAddress).safeIncreaseAllowance( masterchefAddress, uint256(-1) ); IERC20(earnedAddress).safeApprove(uniRouterAddress, uint256(0)); IERC20(earnedAddress).safeIncreaseAllowance( uniRouterAddress, uint256(-1) ); IERC20(wmaticAddress).safeApprove(uniRouterAddress, uint256(0)); IERC20(wmaticAddress).safeIncreaseAllowance( uniRouterAddress, uint256(-1) ); IERC20(token0Address).safeApprove(uniRouterAddress, uint256(0)); IERC20(token0Address).safeIncreaseAllowance( uniRouterAddress, uint256(-1) ); IERC20(token1Address).safeApprove(uniRouterAddress, uint256(0)); IERC20(token1Address).safeIncreaseAllowance( uniRouterAddress, uint256(-1) ); IERC20(usdcAddress).safeApprove(rewardAddress, uint256(0)); IERC20(usdcAddress).safeIncreaseAllowance( rewardAddress, uint256(-1) ); } function _emergencyVaultWithdraw() internal override { ISushiStake(masterchefAddress).withdraw(pid, vaultSharesTotal(), address(this)); } function emergencyPanic() external onlyGov { _pause(); ISushiStake(masterchefAddress).emergencyWithdraw(pid, address(this)); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } receive() external payable {} }
Harvest farm tokens Converts farm tokens into want tokens Swap half earned to token0 Swap half earned to token1 Swap half earned to token0 Swap half earned to token1 Get want tokens, ie. add liquidity
function earn() external override nonReentrant whenNotPaused onlyGov { ISushiStake(masterchefAddress).harvest(pid, address(this)); uint256 earnedAmt = IERC20(earnedAddress).balanceOf(address(this)); uint256 wmaticAmt = IERC20(wmaticAddress).balanceOf(address(this)); if (earnedAmt > 0) { earnedAmt = distributeFees(earnedAmt, earnedAddress); earnedAmt = distributeRewards(earnedAmt, earnedAddress); earnedAmt = buyBack(earnedAmt, earnedAddress); if (earnedAddress != token0Address) { _safeSwap( earnedAmt.div(2), earnedToToken0Path, address(this) ); } if (earnedAddress != token1Address) { _safeSwap( earnedAmt.div(2), earnedToToken1Path, address(this) ); } } if (wmaticAmt > 0) { wmaticAmt = distributeFees(wmaticAmt, wmaticAddress); wmaticAmt = distributeRewards(wmaticAmt, wmaticAddress); wmaticAmt = buyBack(wmaticAmt, wmaticAddress); if (wmaticAddress != token0Address) { _safeSwap( wmaticAmt.div(2), wmaticToToken0Path, address(this) ); } if (wmaticAddress != token1Address) { _safeSwap( wmaticAmt.div(2), wmaticToToken1Path, address(this) ); } } if (earnedAmt > 0 || wmaticAmt > 0) { uint256 token0Amt = IERC20(token0Address).balanceOf(address(this)); uint256 token1Amt = IERC20(token1Address).balanceOf(address(this)); if (token0Amt > 0 && token1Amt > 0) { IUniRouter02(uniRouterAddress).addLiquidity( token0Address, token1Address, token0Amt, token1Amt, 0, 0, address(this), now.add(600) ); } lastEarnBlock = block.number; _farm(); } }
14,030,012
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "openzeppelin-solidity-2.3.0/contracts/token/ERC20/SafeERC20.sol"; // Inheritance import "./Owned.sol"; import "./MixinSystemSettings.sol"; import "./interfaces/ICollateralLoan.sol"; // Libraries import "./SafeDecimalMath.sol"; // Internal references import "./interfaces/ICollateralUtil.sol"; import "./interfaces/ICollateralManager.sol"; import "./interfaces/ISystemStatus.sol"; import "./interfaces/IFeePool.sol"; import "./interfaces/IIssuer.sol"; import "./interfaces/ISynth.sol"; import "./interfaces/IExchangeRates.sol"; import "./interfaces/IExchanger.sol"; import "./interfaces/IShortingRewards.sol"; contract Collateral is ICollateralLoan, Owned, MixinSystemSettings { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SafeDecimalMath for uint; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ bytes32 private constant sUSD = "sUSD"; // ========== STATE VARIABLES ========== // The synth corresponding to the collateral. bytes32 public collateralKey; // Stores open loans. mapping(uint => Loan) public loans; ICollateralManager public manager; // The synths that this contract can issue. bytes32[] public synths; // Map from currency key to synth contract name. mapping(bytes32 => bytes32) public synthsByKey; // Map from currency key to the shorting rewards contract mapping(bytes32 => address) public shortingRewards; // ========== SETTER STATE VARIABLES ========== // The minimum collateral ratio required to avoid liquidation. uint public minCratio; // The minimum amount of collateral to create a loan. uint public minCollateral; bool public canOpenLoans = true; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; bytes32 private constant CONTRACT_SYNTHSUSD = "SynthsUSD"; bytes32 private constant CONTRACT_COLLATERALUTIL = "CollateralUtil"; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, ICollateralManager _manager, address _resolver, bytes32 _collateralKey, uint _minCratio, uint _minCollateral ) public Owned(_owner) MixinSystemSettings(_resolver) { manager = _manager; collateralKey = _collateralKey; minCratio = _minCratio; minCollateral = _minCollateral; } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](6); newAddresses[0] = CONTRACT_FEEPOOL; newAddresses[1] = CONTRACT_EXRATES; newAddresses[2] = CONTRACT_EXCHANGER; newAddresses[3] = CONTRACT_SYSTEMSTATUS; newAddresses[4] = CONTRACT_SYNTHSUSD; newAddresses[5] = CONTRACT_COLLATERALUTIL; bytes32[] memory combined = combineArrays(existingAddresses, newAddresses); addresses = combineArrays(combined, synths); } /* ---------- Related Contracts ---------- */ function _systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function _synth(bytes32 synthName) internal view returns (ISynth) { return ISynth(requireAndGetAddress(synthName)); } function _synthsUSD() internal view returns (ISynth) { return ISynth(requireAndGetAddress(CONTRACT_SYNTHSUSD)); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function _exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function _feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function _collateralUtil() internal view returns (ICollateralUtil) { return ICollateralUtil(requireAndGetAddress(CONTRACT_COLLATERALUTIL)); } /* ---------- Public Views ---------- */ function collateralRatio(uint id) public view returns (uint cratio) { Loan memory loan = loans[id]; return _collateralUtil().getCollateralRatio(loan, collateralKey); } function liquidationAmount(uint id) public view returns (uint liqAmount) { Loan memory loan = loans[id]; return _collateralUtil().liquidationAmount(loan, minCratio, collateralKey); } // The maximum number of synths issuable for this amount of collateral function maxLoan(uint amount, bytes32 currency) public view returns (uint max) { return _collateralUtil().maxLoan(amount, currency, minCratio, collateralKey); } function areSynthsAndCurrenciesSet(bytes32[] calldata _synthNamesInResolver, bytes32[] calldata _synthKeys) external view returns (bool) { if (synths.length != _synthNamesInResolver.length) { return false; } for (uint i = 0; i < _synthNamesInResolver.length; i++) { bytes32 synthName = _synthNamesInResolver[i]; if (synths[i] != synthName) { return false; } if (synthsByKey[_synthKeys[i]] != synths[i]) { return false; } } return true; } /* ---------- UTILITIES ---------- */ // Check the account has enough of the synth to make the payment function _checkSynthBalance( address payer, bytes32 key, uint amount ) internal view { require(IERC20(address(_synth(synthsByKey[key]))).balanceOf(payer) >= amount, "Not enough balance"); } // We set the interest index to 0 to indicate the loan has been closed. function _checkLoanAvailable(Loan memory loan) internal view { _isLoanOpen(loan.interestIndex); require(loan.lastInteraction.add(getInteractionDelay(address(this))) <= block.timestamp, "Recently interacted"); } function _isLoanOpen(uint interestIndex) internal pure { require(interestIndex != 0, "Loan is closed"); } function _issuanceRatio() internal view returns (uint ratio) { ratio = SafeDecimalMath.unit().divideDecimalRound(minCratio); } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Synths ---------- */ function addSynths(bytes32[] calldata _synthNamesInResolver, bytes32[] calldata _synthKeys) external onlyOwner { require(_synthNamesInResolver.length == _synthKeys.length, "Array length mismatch"); for (uint i = 0; i < _synthNamesInResolver.length; i++) { bytes32 synthName = _synthNamesInResolver[i]; synths.push(synthName); synthsByKey[_synthKeys[i]] = synthName; } // ensure cache has the latest rebuildCache(); } /* ---------- Rewards Contracts ---------- */ function addRewardsContracts(address rewardsContract, bytes32 synth) external onlyOwner { shortingRewards[synth] = rewardsContract; } /* ---------- LOAN INTERACTIONS ---------- */ function _open( uint collateral, uint amount, bytes32 currency, bool short ) internal rateIsValid issuanceIsActive returns (uint id) { // 0. Check if able to open loans. require(canOpenLoans, "Open disabled"); // 1. We can only issue certain synths. require(synthsByKey[currency] > 0, "Not allowed to issue"); // 2. Make sure the synth rate is not invalid. require(!_exchangeRates().rateIsInvalid(currency), "Invalid rate"); // 3. Collateral >= minimum collateral size. require(collateral >= minCollateral, "Not enough collateral"); // 4. Check we haven't hit the debt cap for non snx collateral. (bool canIssue, bool anyRateIsInvalid) = manager.exceedsDebtLimit(amount, currency); // 5. Check if we've hit the debt cap or any rate is invalid. require(canIssue && !anyRateIsInvalid, "Debt limit or invalid rate"); // 6. Require requested loan < max loan. require(amount <= maxLoan(collateral, currency), "Exceed max borrow power"); // 7. This fee is denominated in the currency of the loan. uint issueFee = amount.multiplyDecimalRound(getIssueFeeRate(address(this))); // 8. Calculate the minting fee and subtract it from the loan amount. uint loanAmountMinusFee = amount.sub(issueFee); // 9. Get a Loan ID. id = manager.getNewLoanId(); // 10. Create the loan struct. loans[id] = Loan({ id: id, account: msg.sender, collateral: collateral, currency: currency, amount: amount, short: short, accruedInterest: 0, interestIndex: 0, lastInteraction: block.timestamp }); // 11. Accrue interest on the loan. _accrueInterest(loans[id]); // 12. Pay the minting fees to the fee pool. _payFees(issueFee, currency); // 13. If its short, convert back to sUSD, otherwise issue the loan. if (short) { _synthsUSD().issue(msg.sender, _exchangeRates().effectiveValue(currency, loanAmountMinusFee, sUSD)); manager.incrementShorts(currency, amount); if (shortingRewards[currency] != address(0)) { IShortingRewards(shortingRewards[currency]).enrol(msg.sender, amount); } } else { _synth(synthsByKey[currency]).issue(msg.sender, loanAmountMinusFee); manager.incrementLongs(currency, amount); } // 14. Emit event for the newly opened loan. emit LoanCreated(msg.sender, id, amount, collateral, currency, issueFee); } function _close(address borrower, uint id) internal rateIsValid issuanceIsActive returns (uint amount, uint collateral) { // 0. Get the loan and accrue interest. Loan storage loan = _getLoanAndAccrueInterest(id, borrower); // 1. Check loan is open and last interaction time. _checkLoanAvailable(loan); // 2. Record loan as closed. (amount, collateral) = _closeLoan(borrower, borrower, loan); // 3. Emit the event for the closed loan. emit LoanClosed(borrower, id); } function _closeByLiquidation( address borrower, address liquidator, Loan storage loan ) internal returns (uint amount, uint collateral) { (amount, collateral) = _closeLoan(borrower, liquidator, loan); // Emit the event for the loan closed by liquidation. emit LoanClosedByLiquidation(borrower, loan.id, liquidator, amount, collateral); } function _closeLoan( address borrower, address liquidator, Loan storage loan ) internal returns (uint amount, uint collateral) { // 0. Work out the total amount owing on the loan. uint total = loan.amount.add(loan.accruedInterest); // 1. Store this for the event. amount = loan.amount; // 2. Return collateral to the child class so it knows how much to transfer. collateral = loan.collateral; // 3. Check that the liquidator has enough synths. _checkSynthBalance(liquidator, loan.currency, total); // 4. Burn the synths. _synth(synthsByKey[loan.currency]).burn(liquidator, total); // 5. Tell the manager. if (loan.short) { manager.decrementShorts(loan.currency, loan.amount); if (shortingRewards[loan.currency] != address(0)) { IShortingRewards(shortingRewards[loan.currency]).withdraw(borrower, loan.amount); } } else { manager.decrementLongs(loan.currency, loan.amount); } // 6. Pay fees. _payFees(loan.accruedInterest, loan.currency); // 7. Record loan as closed. _recordLoanAsClosed(loan); } function _closeLoanByRepayment(address borrower, uint id) internal returns (uint amount, uint collateral) { // 0. Get the loan. Loan storage loan = loans[id]; // 1. Repay the loan with its collateral. (amount, collateral) = _repayWithCollateral(borrower, id, loan.amount); // 2. Pay the service fee for collapsing the loan. uint serviceFee = amount.multiplyDecimalRound(getCollapseFeeRate(address(this))); _payFees(serviceFee, sUSD); collateral = collateral.sub(serviceFee); // 3. Record loan as closed. _recordLoanAsClosed(loan); // 4. Emit the event for the loan closed by repayment. emit LoanClosedByRepayment(borrower, id, amount, collateral); } function _deposit( address account, uint id, uint amount ) internal rateIsValid issuanceIsActive returns (uint, uint) { // 0. They sent some value > 0 require(amount > 0, "Deposit must be above 0"); // 1. Get the loan. // Owner is not important here, as it is a donation to the collateral of the loan Loan storage loan = loans[id]; // 2. Check loan hasn't been closed or liquidated. _isLoanOpen(loan.interestIndex); // 3. Accrue interest on the loan. _accrueInterest(loan); // 4. Add the collateral. loan.collateral = loan.collateral.add(amount); // 5. Emit the event for the deposited collateral. emit CollateralDeposited(account, id, amount, loan.collateral); return (loan.amount, loan.collateral); } function _withdraw(uint id, uint amount) internal rateIsValid issuanceIsActive returns (uint, uint) { // 0. Get the loan and accrue interest. Loan storage loan = _getLoanAndAccrueInterest(id, msg.sender); // 1. Subtract the collateral. loan.collateral = loan.collateral.sub(amount); // 2. Check that the new amount does not put them under the minimum c ratio. _checkLoanRatio(loan); // 3. Emit the event for the withdrawn collateral. emit CollateralWithdrawn(msg.sender, id, amount, loan.collateral); return (loan.amount, loan.collateral); } function _liquidate( address borrower, uint id, uint payment ) internal rateIsValid issuanceIsActive returns (uint collateralLiquidated) { require(payment > 0, "Payment must be above 0"); // 0. Get the loan and accrue interest. Loan storage loan = _getLoanAndAccrueInterest(id, borrower); // 1. Check they have enough balance to make the payment. _checkSynthBalance(msg.sender, loan.currency, payment); // 2. Check they are eligible for liquidation. // Note: this will revert if collateral is 0, however that should only be possible if the loan amount is 0. require(_collateralUtil().getCollateralRatio(loan, collateralKey) < minCratio, "Cratio above liq ratio"); // 3. Determine how much needs to be liquidated to fix their c ratio. uint liqAmount = _collateralUtil().liquidationAmount(loan, minCratio, collateralKey); // 4. Only allow them to liquidate enough to fix the c ratio. uint amountToLiquidate = liqAmount < payment ? liqAmount : payment; // 5. Work out the total amount owing on the loan. uint amountOwing = loan.amount.add(loan.accruedInterest); // 6. If its greater than the amount owing, we need to close the loan. if (amountToLiquidate >= amountOwing) { (, collateralLiquidated) = _closeByLiquidation(borrower, msg.sender, loan); return collateralLiquidated; } // 7. Check they have enough balance to liquidate the loan. _checkSynthBalance(msg.sender, loan.currency, amountToLiquidate); // 8. Process the payment to workout interest/principal split. _processPayment(loan, amountToLiquidate); // 9. Work out how much collateral to redeem. collateralLiquidated = _collateralUtil().collateralRedeemed(loan.currency, amountToLiquidate, collateralKey); loan.collateral = loan.collateral.sub(collateralLiquidated); // 10. Burn the synths from the liquidator. _synth(synthsByKey[loan.currency]).burn(msg.sender, amountToLiquidate); // 11. Emit the event for the partial liquidation. emit LoanPartiallyLiquidated(borrower, id, msg.sender, amountToLiquidate, collateralLiquidated); } function _repay( address borrower, address repayer, uint id, uint payment ) internal rateIsValid issuanceIsActive returns (uint, uint) { // 0. Get the loan. // Owner is not important here, as it is a donation to repay the loan. Loan storage loan = loans[id]; // 1. Check loan is open and last interaction time. _checkLoanAvailable(loan); // 2. Check the spender has enough synths to make the repayment _checkSynthBalance(repayer, loan.currency, payment); // 3. Accrue interest on the loan. _accrueInterest(loan); // 4. Process the payment. _processPayment(loan, payment); // 5. Burn synths from the payer _synth(synthsByKey[loan.currency]).burn(repayer, payment); // 6. Update the last interaction time. loan.lastInteraction = block.timestamp; // 7. Emit the event the repayment. emit LoanRepaymentMade(borrower, repayer, id, payment, loan.amount); // 8. Return the loan amount and collateral after repaying. return (loan.amount, loan.collateral); } function _repayWithCollateral( address borrower, uint id, uint payment ) internal rateIsValid issuanceIsActive returns (uint amount, uint collateral) { // 0. Get the loan to repay and accrue interest. Loan storage loan = _getLoanAndAccrueInterest(id, borrower); // 1. Check loan is open and last interaction time. _checkLoanAvailable(loan); // 2. Repay the accrued interest. payment = payment.add(loan.accruedInterest); // 3. Make sure they are not overpaying. require(payment <= loan.amount.add(loan.accruedInterest), "Payment too high"); // 4. Get the expected amount for the exchange from borrowed synth -> sUSD. (uint expectedAmount, uint fee, ) = _exchanger().getAmountsForExchange(payment, loan.currency, sUSD); // 5. Reduce the collateral by the amount repaid (minus the exchange fees). loan.collateral = loan.collateral.sub(expectedAmount); // 6. Process the payment and pay the exchange fees if needed. _processPayment(loan, payment); _payFees(fee, sUSD); // 7. Update the last interaction time. loan.lastInteraction = block.timestamp; // 8. Emit the event for the collateral repayment. emit LoanRepaymentMade(borrower, borrower, id, payment, loan.amount); // 9. Return the amount repaid and the remaining collateral. return (payment, loan.collateral); } function _draw(uint id, uint amount) internal rateIsValid issuanceIsActive returns (uint, uint) { // 0. Get the loan and accrue interest. Loan storage loan = _getLoanAndAccrueInterest(id, msg.sender); // 1. Check last interaction time. _checkLoanAvailable(loan); // 2. Add the requested amount. loan.amount = loan.amount.add(amount); // 3. If it is below the minimum, don't allow this draw. _checkLoanRatio(loan); // 4. This fee is denominated in the currency of the loan uint issueFee = amount.multiplyDecimalRound(getIssueFeeRate(address(this))); // 5. Calculate the minting fee and subtract it from the draw amount uint amountMinusFee = amount.sub(issueFee); // 6. If its short, issue the synths. if (loan.short) { manager.incrementShorts(loan.currency, amount); _synthsUSD().issue(msg.sender, _exchangeRates().effectiveValue(loan.currency, amountMinusFee, sUSD)); if (shortingRewards[loan.currency] != address(0)) { IShortingRewards(shortingRewards[loan.currency]).enrol(msg.sender, amount); } } else { manager.incrementLongs(loan.currency, amount); _synth(synthsByKey[loan.currency]).issue(msg.sender, amountMinusFee); } // 7. Pay the minting fees to the fee pool _payFees(issueFee, loan.currency); // 8. Update the last interaction time. loan.lastInteraction = block.timestamp; // 9. Emit the event for the draw down. emit LoanDrawnDown(msg.sender, id, amount); return (loan.amount, loan.collateral); } // Update the cumulative interest rate for the currency that was interacted with. function _accrueInterest(Loan storage loan) internal { (uint differential, uint newIndex) = manager.accrueInterest(loan.interestIndex, loan.currency, loan.short); // If the loan was just opened, don't record any interest. Otherwise multiply by the amount outstanding. uint interest = loan.interestIndex == 0 ? 0 : loan.amount.multiplyDecimal(differential); // Update the loan. loan.accruedInterest = loan.accruedInterest.add(interest); loan.interestIndex = newIndex; } // Works out the amount of interest and principal after a repayment is made. function _processPayment(Loan storage loan, uint payment) internal { require(payment > 0, "Payment must be above 0"); if (loan.accruedInterest > 0) { uint interestPaid = payment > loan.accruedInterest ? loan.accruedInterest : payment; loan.accruedInterest = loan.accruedInterest.sub(interestPaid); payment = payment.sub(interestPaid); _payFees(interestPaid, loan.currency); } // If there is more payment left after the interest, pay down the principal. if (payment > 0) { loan.amount = loan.amount.sub(payment); // And get the manager to reduce the total long/short balance. if (loan.short) { manager.decrementShorts(loan.currency, payment); if (shortingRewards[loan.currency] != address(0)) { IShortingRewards(shortingRewards[loan.currency]).withdraw(loan.account, payment); } } else { manager.decrementLongs(loan.currency, payment); } } } // Take an amount of fees in a certain synth and convert it to sUSD before paying the fee pool. function _payFees(uint amount, bytes32 synth) internal { if (amount > 0) { if (synth != sUSD) { amount = _exchangeRates().effectiveValue(synth, amount, sUSD); } _synthsUSD().issue(_feePool().FEE_ADDRESS(), amount); _feePool().recordFeePaid(amount); } } function _recordLoanAsClosed(Loan storage loan) internal { loan.amount = 0; loan.collateral = 0; loan.accruedInterest = 0; loan.interestIndex = 0; loan.lastInteraction = block.timestamp; } function _getLoanAndAccrueInterest(uint id, address owner) internal returns (Loan storage loan) { loan = loans[id]; // Make sure the loan is open and it is the borrower. _isLoanOpen(loan.interestIndex); require(loan.account == owner, "Must be borrower"); _accrueInterest(loan); } function _checkLoanRatio(Loan storage loan) internal view { if (loan.amount == 0) { return; } require(collateralRatio(loan.id) > minCratio, "Cratio too low"); } // ========== MODIFIERS ========== modifier rateIsValid() { _requireRateIsValid(); _; } function _requireRateIsValid() private view { require(!_exchangeRates().rateIsInvalid(collateralKey), "Invalid rate"); } modifier issuanceIsActive() { _requireIssuanceIsActive(); _; } function _requireIssuanceIsActive() private view { _systemStatus().requireIssuanceActive(); } // ========== EVENTS ========== // Loans event LoanCreated(address indexed account, uint id, uint amount, uint collateral, bytes32 currency, uint issuanceFee); event LoanClosed(address indexed account, uint id); event CollateralDeposited(address indexed account, uint id, uint amountDeposited, uint collateralAfter); event CollateralWithdrawn(address indexed account, uint id, uint amountWithdrawn, uint collateralAfter); event LoanRepaymentMade(address indexed account, address indexed repayer, uint id, uint amountRepaid, uint amountAfter); event LoanDrawnDown(address indexed account, uint id, uint amount); event LoanPartiallyLiquidated( address indexed account, uint id, address liquidator, uint amountLiquidated, uint collateralLiquidated ); event LoanClosedByLiquidation( address indexed account, uint id, address indexed liquidator, uint amountLiquidated, uint collateralLiquidated ); event LoanClosedByRepayment(address indexed account, uint id, uint amountRepaid, uint collateralAfter); }
0. They sent some value > 0 1. Get the loan. Owner is not important here, as it is a donation to the collateral of the loan 2. Check loan hasn't been closed or liquidated. 3. Accrue interest on the loan. 4. Add the collateral. 5. Emit the event for the deposited collateral.
function _deposit( address account, uint id, uint amount ) internal rateIsValid issuanceIsActive returns (uint, uint) { require(amount > 0, "Deposit must be above 0"); Loan storage loan = loans[id]; _isLoanOpen(loan.interestIndex); _accrueInterest(loan); loan.collateral = loan.collateral.add(amount); emit CollateralDeposited(account, id, amount, loan.collateral); return (loan.amount, loan.collateral); }
6,456,523
./full_match/44787/0xFd5487808Ee8782831a7f71FF2497068C0b8BB9e/sources/contracts/StarFarm.sol
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; pool.lpToken.safeTransfer(_msgSender(), user.amount); emit EmergencyWithdraw(_msgSender(), _pid, user.amount); user.amount = 0; user.rewardDebt = 0; }
13,243,485
/** * Copyright 2017-2019, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.3; pragma experimental ABIEncoderV2; import "../openzeppelin-solidity/Math.sol"; import "../proxy/BZxProxiable.sol"; import "../shared/OrderTakingFunctions.sol"; contract OrderTaking_MiscFunctions is BZxStorage, BZxProxiable, OrderTakingFunctions { using SafeMath for uint256; constructor() public {} function() external { revert("fallback not allowed"); } function initialize( address _target) public onlyOwner { targets[bytes4(keccak256("cancelLoanOrder(address[8],uint256[11],bytes,uint256)"))] = _target; targets[bytes4(keccak256("cancelLoanOrderWithHash(bytes32,uint256)"))] = _target; targets[bytes4(keccak256("pushLoanOrderOnChain(address[8],uint256[11],bytes,bytes)"))] = _target; targets[bytes4(keccak256("preSign(address,address[8],uint256[11],bytes,bytes)"))] = _target; targets[bytes4(keccak256("preSignWithHash(address,bytes32,bytes)"))] = _target; targets[bytes4(keccak256("toggleDelegateApproved(address,bool)"))] = _target; targets[bytes4(keccak256("toggleProtocolDelegateApproved(address,bool)"))] = _target; targets[bytes4(keccak256("getLoanTokenFillable(bytes32)"))] = _target; targets[bytes4(keccak256("getLoanOrderHash(address[8],uint256[11],bytes)"))] = _target; targets[bytes4(keccak256("isValidSignature(address,bytes32,bytes)"))] = _target; targets[bytes4(keccak256("getInitialCollateralRequired(address,address,address,uint256,uint256)"))] = _target; } /// @dev Cancels remaining (untaken) loan /// @param orderAddresses Array of order's makerAddress, loanTokenAddress, interestTokenAddress, collateralTokenAddress, feeRecipientAddress, oracleAddress, takerAddress, tradeTokenToFillAddress. /// @param orderValues Array of order's loanTokenAmount, interestAmount, initialMarginAmount, maintenanceMarginAmount, lenderRelayFee, traderRelayFee, maxDurationUnixTimestampSec, expirationUnixTimestampSec, makerRole (0=lender, 1=trader), withdrawOnOpen, and salt. /// @param oracleData An arbitrary length bytes stream to pass to the oracle. /// @param cancelLoanTokenAmount The amount of remaining unloaned token to cancel. /// @return The amount of loan token canceled. function cancelLoanOrder( address[8] calldata orderAddresses, uint256[11] calldata orderValues, bytes calldata oracleData, uint256 cancelLoanTokenAmount) external nonReentrant tracksGas returns (uint256) { bytes32 loanOrderHash = _getLoanOrderHash(orderAddresses, orderValues, oracleData); require(orderAddresses[0] == msg.sender, "BZxOrderTaking::cancelLoanOrder: makerAddress != msg.sender"); require(orderValues[0] > 0 && cancelLoanTokenAmount > 0, "BZxOrderTaking::cancelLoanOrder: invalid params"); if (orderValues[7] > 0 && block.timestamp >= orderValues[7]) { _removeLoanOrder(loanOrderHash, address(0)); return 0; } uint256 remainingCancelAmount = orderValues[0].sub(orderCancelledAmounts[loanOrderHash]); uint256 cancelledLoanTokenAmount = Math.min256(cancelLoanTokenAmount, remainingCancelAmount); if (cancelledLoanTokenAmount == 0) { // none left to cancel return 0; } orderCancelledAmounts[loanOrderHash] = orderCancelledAmounts[loanOrderHash].add(cancelledLoanTokenAmount); uint256 remainingLoanTokenAmount = orderValues[0].sub(_getUnavailableLoanTokenAmount(loanOrderHash)); if (remainingLoanTokenAmount == 0) { _removeLoanOrder(loanOrderHash, address(0)); } emit LogLoanCancelled( msg.sender, cancelledLoanTokenAmount, remainingLoanTokenAmount, loanOrderHash ); return cancelledLoanTokenAmount; } /// @dev Cancels remaining (untaken) loan /// @param loanOrderHash A unique hash representing the loan order. /// @param cancelLoanTokenAmount The amount of remaining unloaned token to cancel. /// @return The amount of loan token canceled. function cancelLoanOrderWithHash( bytes32 loanOrderHash, uint256 cancelLoanTokenAmount) external nonReentrant tracksGas returns (uint256) { LoanOrder memory loanOrder = orders[loanOrderHash]; if (loanOrder.loanTokenAddress == address(0)) { revert("BZxOrderTaking::cancelLoanOrderWithHash: loanOrder.loanTokenAddress == address(0)"); } LoanOrderAux memory loanOrderAux = orderAux[loanOrderHash]; require(loanOrderAux.makerAddress == msg.sender, "BZxOrderTaking::cancelLoanOrderWithHash: loanOrderAux.makerAddress != msg.sender"); require(loanOrder.loanTokenAmount > 0 && cancelLoanTokenAmount > 0, "BZxOrderTaking::cancelLoanOrderWithHash: invalid params"); if (loanOrderAux.expirationUnixTimestampSec > 0 && block.timestamp >= loanOrderAux.expirationUnixTimestampSec) { _removeLoanOrder(loanOrder.loanOrderHash, address(0)); return 0; } uint256 remainingCancelAmount = loanOrder.loanTokenAmount.sub(orderCancelledAmounts[loanOrder.loanOrderHash]); uint256 cancelledLoanTokenAmount = Math.min256(cancelLoanTokenAmount, remainingCancelAmount); if (cancelledLoanTokenAmount == 0) { // none left to cancel return 0; } orderCancelledAmounts[loanOrder.loanOrderHash] = orderCancelledAmounts[loanOrder.loanOrderHash].add(cancelledLoanTokenAmount); uint256 remainingLoanTokenAmount = loanOrder.loanTokenAmount.sub(_getUnavailableLoanTokenAmount(loanOrder.loanOrderHash)); if (remainingLoanTokenAmount == 0) { _removeLoanOrder(loanOrder.loanOrderHash, address(0)); } emit LogLoanCancelled( msg.sender, cancelledLoanTokenAmount, remainingLoanTokenAmount, loanOrder.loanOrderHash ); return cancelledLoanTokenAmount; } /// @dev Pushes an order on chain /// @param orderAddresses Array of order's makerAddress, loanTokenAddress, interestTokenAddress, collateralTokenAddress, feeRecipientAddress, oracleAddress, takerAddress, tradeTokenToFillAddress. /// @param orderValues Array of order's loanTokenAmount, interestAmount, initialMarginAmount, maintenanceMarginAmount, lenderRelayFee, traderRelayFee, maxDurationUnixTimestampSec, expirationUnixTimestampSec, makerRole (0=lender, 1=trader), withdrawOnOpen, and salt. /// @param oracleData An arbitrary length bytes stream to pass to the oracle. /// @param signature ECDSA signature in raw bytes (rsv). /// @return A unique hash representing the loan order. function pushLoanOrderOnChain( address[8] calldata orderAddresses, uint256[11] calldata orderValues, bytes calldata oracleData, bytes calldata signature) external nonReentrant tracksGas returns (bytes32) { bytes32 loanOrderHash = _addLoanOrder( msg.sender, orderAddresses, orderValues, oracleData, signature); require(!orderListIndex[loanOrderHash][address(0)].isSet, "BZxOrderTaking::pushLoanOrderOnChain: this order is already on chain"); if (orderValues[0] > 0) { // record of fillable (non-expired/unfilled) orders orderList[address(0)].push(loanOrderHash); orderListIndex[loanOrderHash][address(0)] = ListIndex({ index: orderList[address(0)].length-1, isSet: true }); } return loanOrderHash; } /// @dev Approves a hash on-chain using any valid signature type. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param signer Address that should have signed the hash generated by the loanOrder parameters given. /// @param orderAddresses Array of order's makerAddress, loanTokenAddress, interestTokenAddress, collateralTokenAddress, feeRecipientAddress, oracleAddress, takerAddress, tradeTokenToFillAddress. /// @param orderValues Array of order's loanTokenAmount, interestAmount, initialMarginAmount, maintenanceMarginAmount, lenderRelayFee, traderRelayFee, maxDurationUnixTimestampSec, expirationUnixTimestampSec, makerRole (0=lender, 1=trader), withdrawOnOpen, and salt. /// @param oracleData An arbitrary length bytes stream to pass to the oracle. /// @param signature Proof that the hash has been signed by signer. function preSign( address signer, address[8] calldata orderAddresses, uint256[11] calldata orderValues, bytes calldata oracleData, bytes calldata signature) external nonReentrant { _preSign( signer, _getLoanOrderHash(orderAddresses, orderValues, oracleData), signature ); } /// @dev Approves a hash on-chain using any valid signature type. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param signer Address that should have signed the given hash. /// @param hash Signed Keccak-256 hash. /// @param signature Proof that the hash has been signed by signer. function preSignWithHash( address signer, bytes32 hash, bytes calldata signature) external nonReentrant { _preSign( signer, hash, signature ); } /// @dev Toggles approval of a deletate that can fill orders on behalf of another user /// @param delegate The delegate address /// @param isApproved If true, the delegate is approved. If false, the delegate is not approved function toggleDelegateApproved( address delegate, bool isApproved) external { allowedValidators[msg.sender][delegate] = isApproved; } /// @dev Toggles approval of a protocol deletate that can fill orders on behalf of another user when requested by that user /// @param delegate The delegate address /// @param isApproved If true, the delegate is approved. If false, the delegate is not approved function toggleProtocolDelegateApproved( address delegate, bool isApproved) external onlyOwner { allowedValidators[address(0)][delegate] = isApproved; } /// @dev Returns the amount of fillable loan token for an order /// @param loanOrderHash A unique hash representing the loan order /// @return The amount of loan token fillable function getLoanTokenFillable( bytes32 loanOrderHash) public view returns (uint256) { // _getUnavailableLoanTokenAmount will never return a value greater than orders[loanOrderHash].loanTokenAmount return orders[loanOrderHash].loanTokenAmount.sub(_getUnavailableLoanTokenAmount(loanOrderHash)); } /// @dev Calculates Keccak-256 hash of order with specified parameters. /// @param orderAddresses Array of order's makerAddress, loanTokenAddress, interestTokenAddress, collateralTokenAddress, feeRecipientAddress, oracleAddress, takerAddress, tradeTokenToFillAddress. /// @param orderValues Array of order's loanTokenAmount, interestAmount, initialMarginAmount, maintenanceMarginAmount, lenderRelayFee, traderRelayFee, maxDurationUnixTimestampSec, expirationUnixTimestampSec, makerRole (0=lender, 1=trader), withdrawOnOpen, and salt. /// @param oracleData An arbitrary length bytes stream to pass to the oracle. /// @return Keccak-256 hash of loanOrder. function getLoanOrderHash( address[8] memory orderAddresses, uint256[11] memory orderValues, bytes memory oracleData) public view returns (bytes32) { return _getLoanOrderHash(orderAddresses, orderValues, oracleData); } /// @dev Verifies that an order signature is valid. /// @param signer address of signer. /// @param hash Signed Keccak-256 hash. /// @param signature ECDSA signature in raw bytes (rsv) + signatureType. /// @return Validity of order signature. function isValidSignature( address signer, bytes32 hash, bytes memory signature) public view returns (bool) { return _isValidSignature( signer, hash, signature); } /// @dev Calculates the initial collateral required to open the loan. /// @param collateralTokenAddress The collateral token used by the trader. /// @param oracleAddress The oracle address specified in the loan order. /// @param loanTokenAmountFilled The amount of loan token borrowed. /// @param initialMarginAmount The initial margin percentage amount (i.e. 50000000000000000000 == 50%) /// @return The minimum collateral requirement to open the loan. function getInitialCollateralRequired( address loanTokenAddress, address collateralTokenAddress, address oracleAddress, uint256 loanTokenAmountFilled, uint256 initialMarginAmount) public view returns (uint256 collateralTokenAmount) { collateralTokenAmount = _getCollateralRequired( loanTokenAddress, collateralTokenAddress, oracleAddress, loanTokenAmountFilled, initialMarginAmount); } function _preSign( address signer, bytes32 hash, bytes memory signature) internal { if (signer != msg.sender) { require( _isValidSignature( signer, hash, signature ), "INVALID_SIGNATURE" ); } preSigned[hash][signer] = true; } }
Pushes an order on chain orderAddresses Array of order's makerAddress, loanTokenAddress, interestTokenAddress, collateralTokenAddress, feeRecipientAddress, oracleAddress, takerAddress, tradeTokenToFillAddress. orderValues Array of order's loanTokenAmount, interestAmount, initialMarginAmount, maintenanceMarginAmount, lenderRelayFee, traderRelayFee, maxDurationUnixTimestampSec, expirationUnixTimestampSec, makerRole (0=lender, 1=trader), withdrawOnOpen, and salt. oracleData An arbitrary length bytes stream to pass to the oracle. signature ECDSA signature in raw bytes (rsv). return A unique hash representing the loan order. record of fillable (non-expired/unfilled) orders
function pushLoanOrderOnChain( address[8] calldata orderAddresses, uint256[11] calldata orderValues, bytes calldata oracleData, bytes calldata signature) external nonReentrant tracksGas returns (bytes32) { bytes32 loanOrderHash = _addLoanOrder( msg.sender, orderAddresses, orderValues, oracleData, signature); require(!orderListIndex[loanOrderHash][address(0)].isSet, "BZxOrderTaking::pushLoanOrderOnChain: this order is already on chain"); if (orderValues[0] > 0) { orderList[address(0)].push(loanOrderHash); orderListIndex[loanOrderHash][address(0)] = ListIndex({ index: orderList[address(0)].length-1, isSet: true }); } return loanOrderHash; }
12,957,431
pragma solidity ^0.4.20; import "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol"; //".oraclizeAPI_0.4.sol"; //import "github.com/oraclize/ethereum-api/oraclizeAPI_0.5.sol"; //"./oraclizeAPI_0.5.sol"; import "github.com/Arachnid/solidity-stringutils/src/strings.sol"; //"./strings.sol"; contract BluzelleClient is usingOraclize { enum opType {read, create, update, remove} struct pendingOperation { opType op; string key; } using strings for *; mapping(bytes32 => pendingOperation) pendingOps; string uuid; string public apiRead = "http://testnet.bluzelle.com:8080/read/"; string public apiCreate = "http://testnet.bluzelle.com:8080/create/"; string public apiUpdate = "http://testnet.bluzelle.com:8080/update/"; string public apiRemove = "http://testnet.bluzelle.com:8080/delete/"; string constant successPrefix = "ack"; string constant failPrefix = "err"; function setUUID(string _uuid) internal { uuid = _uuid; } function setURL(string _url) internal { apiRead = strConcat(_url,"/read/"); apiCreate = strConcat(_url,"/create/"); apiUpdate = strConcat(_url,"/update/"); apiRemove = strConcat(_url,"/delete/"); } function read(string key) internal { string memory request = strConcat(apiRead,uuid,"/",key); bytes32 id = oraclize_query("URL", request); pendingOps[id] = pendingOperation(opType.read, key); } function remove(string key) internal { string memory request = strConcat(apiRemove,uuid,"/",key); // third parameter makes the request a POST bytes32 id = oraclize_query("URL", request, "-"); pendingOps[id] = pendingOperation(opType.remove, key); } function update(string key, string data) internal { string memory request = strConcat(apiUpdate,uuid,"/",key); bytes32 id = oraclize_query("URL", request, data); pendingOps[id] = pendingOperation(opType.update, key); } function create(string key, string data) internal { string memory request = strConcat(apiCreate,uuid,"/",key); bytes32 id = oraclize_query("URL", request, data); pendingOps[id] = pendingOperation(opType.create, key); } function readResult(string /*key*/, string /*result*/, bool /*success*/) internal { // Called when a read returns sucessfully } function readFailure(string /*key*/, bool /*success*/) internal { // Called when a read fails (no such key or db unavailable) } function createResponse(string /*key*/, bool /*success*/) internal { // Called when a create returns } function updateResponse(string /*key*/, bool /*success*/) internal { // Called when an update returns } function removeResponse(string /*key*/, bool /*success*/) internal { // Called when a remove returns } // Result from oraclize function __callback(bytes32 myid, string result) public { require(msg.sender == oraclize_cbAddress()); require(pendingOps[myid].key.toSlice().len() > 0); bool success = result.toSlice().startsWith(successPrefix.toSlice()); string memory key = pendingOps[myid].key; opType op = pendingOps[myid].op; if(op == opType.read){ if(success){ readResult( key, result.toSlice().beyond(successPrefix.toSlice()).toString(), success ); }else{ readFailure(key,success); } }else if(op == opType.create){ createResponse(key, success); }else if(op == opType.update){ updateResponse(key, success); }else if(op == opType.remove){ removeResponse(key, success); } delete pendingOps[myid]; } }
Called when a read fails (no such key or db unavailable)
function readFailure(string /*key*/, bool /*success*/) internal { }
1,759,820
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.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 Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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 ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been 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 pragma solidity 0.7.5; /* * @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.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { LS1Types } from '../lib/LS1Types.sol'; /** * @title LS1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract LS1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. LS1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. /// We also restrict other changes which could affect borrowers' repayment plans, such as /// modifications to the epoch schedule, or to borrower allocations. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => LS1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. LS1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => LS1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. Note: The shortfallCounter field is unused. LS1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; /// @dev Information about shortfalls that have occurred. LS1Types.Shortfall[] internal _SHORTFALLS_; // ============ Borrower Accounting ============ /// @dev The units allocated to each borrower. /// @dev Values are represented relative to total allocation, i.e. as hundredeths of a percent. /// Also, the total of the values contained in the mapping must always equal the total /// allocation (i.e. must sum to 10,000). mapping(address => LS1Types.StoredAllocation) internal _BORROWER_ALLOCATIONS_; /// @dev The token balance currently borrowed by the borrower. mapping(address => uint256) internal _BORROWED_BALANCES_; /// @dev The total token balance currently borrowed by borrowers. uint256 internal _TOTAL_BORROWED_BALANCE_; /// @dev Indicates whether a borrower is restricted from new borrowing. mapping(address => bool) internal _BORROWER_RESTRICTIONS_; // ============ Debt Accounting ============ /// @dev The debt balance owed to each staker. mapping(address => uint256) internal _STAKER_DEBT_BALANCES_; /// @dev The debt balance by borrower. mapping(address => uint256) internal _BORROWER_DEBT_BALANCES_; /// @dev The total debt balance of borrowers. uint256 internal _TOTAL_BORROWER_DEBT_BALANCE_; /// @dev The total debt amount repaid and not yet withdrawn. uint256 internal _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @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. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title LS1Types * @author dYdX * * @dev Structs used by the LiquidityStaking contract. */ library LS1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev The parameters representing a shortfall event. * * @param index Fraction of inactive funds converted into debt, scaled by SHORTFALL_INDEX_BASE. * @param epoch The epoch in which the shortfall occurred. */ struct Shortfall { uint16 epoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint224 index; // Note: Save on contract bytecode size by reusing uint224 instead of uint240. } /** * @dev A balance, possibly with a change scheduled for the next epoch. * Also includes cached index information for inactive balances. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. * @param shortfallCounter Incrementing counter of the next shortfall index to be applied. */ struct StoredBalance { uint16 currentEpoch; // Supports at least 1000 years given min epoch length of 6 days. uint112 currentEpochBalance; uint112 nextEpochBalance; uint16 shortfallCounter; // Only for staker inactive balances. At most one shortfall per epoch. } /** * @dev A borrower allocation, possibly with a change scheduled for the next epoch. */ struct StoredAllocation { uint16 currentEpoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint120 currentEpochAllocation; uint120 nextEpochAllocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract LS1Getters is LS1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The token balance currently borrowed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens borrowed. */ function getBorrowedBalance( address borrower ) external view returns (uint256) { return _BORROWED_BALANCES_[borrower]; } /** * @notice The total token balance borrowed by borrowers. * * @return The number of tokens borrowed. */ function getTotalBorrowedBalance() external view returns (uint256) { return _TOTAL_BORROWED_BALANCE_; } /** * @notice The debt balance owed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens owed. */ function getBorrowerDebtBalance( address borrower ) external view returns (uint256) { return _BORROWER_DEBT_BALANCES_[borrower]; } /** * @notice The total debt balance owed by borrowers. * * @return The number of tokens owed. */ function getTotalBorrowerDebtBalance() external view returns (uint256) { return _TOTAL_BORROWER_DEBT_BALANCE_; } /** * @notice The total debt repaid by borrowers and available for stakers to withdraw. * * @return The number of tokens available. */ function getTotalDebtAvailableToWithdraw() external view returns (uint256) { return _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } /** * @notice Check whether a borrower is restricted from new borrowing. * * @param borrower The borrower to check. * * @return Boolean `true` if the borrower is restricted, otherwise `false`. */ function isBorrowingRestrictedForBorrower( address borrower ) external view returns (bool) { return _BORROWER_RESTRICTIONS_[borrower]; } /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (LS1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * Other changes which could affect borrowers' repayment plans are also restricted during * this period. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get information about a shortfall that occurred. * * @param shortfallCounter The array index for the shortfall event to look up. * * @return Struct containing the epoch and shortfall index value. */ function getShortfall( uint256 shortfallCounter ) external view returns (LS1Types.Shortfall memory) { return _SHORTFALLS_[shortfallCounter]; } /** * @notice Get the number of shortfalls that have occurred. * * @return The number of shortfalls that have occurred. */ function getShortfallCount() external view returns (uint256) { return _SHORTFALLS_.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: Apache-2.0 // // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts pragma solidity 0.7.5; pragma abicoder v2; import { IERC20 } from '../../interfaces/IERC20.sol'; import { LS1Admin } from './impl/LS1Admin.sol'; import { LS1Borrowing } from './impl/LS1Borrowing.sol'; import { LS1DebtAccounting } from './impl/LS1DebtAccounting.sol'; import { LS1ERC20 } from './impl/LS1ERC20.sol'; import { LS1Failsafe } from './impl/LS1Failsafe.sol'; import { LS1Getters } from './impl/LS1Getters.sol'; import { LS1Operators } from './impl/LS1Operators.sol'; /** * @title LiquidityStakingV1 * @author dYdX * * @notice Contract for staking tokens, which may then be borrowed by pre-approved borrowers. * * NOTE: Most functions will revert if epoch zero has not started. */ contract LiquidityStakingV1 is LS1Borrowing, LS1DebtAccounting, LS1Admin, LS1Operators, LS1Getters, LS1Failsafe { // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Borrowing(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ function initialize( uint256 interval, uint256 offset, uint256 blackoutWindow ) external initializer { __LS1Roles_init(); __LS1EpochSchedule_init(interval, offset, blackoutWindow); __LS1Rewards_init(); __LS1BorrowerAllocations_init(); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Borrowing } from './LS1Borrowing.sol'; /** * @title LS1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract LS1Admin is LS1Borrowing { using SafeCast for uint256; using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * Reverts if the new interval is less than twice the blackout window. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require(block.timestamp < offset, 'LS1Admin: Started epoch zero'); _setEpochParameters(interval, offset); return; } // Require that we are not currently in a blackout window. require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require(originalCurrentEpoch == newCurrentEpoch, 'LS1Admin: Changed epochs'); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBlackoutWindow(blackoutWindow); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } /** * @notice Change the allocations of certain borrowers. Can be used to add and remove borrowers. * Increases take effect in the next epoch, but decreases will restrict borrowing immediately. * This function cannot be called during the blackout window. * * @param borrowers Array of borrower addresses. * @param newAllocations Array of new allocations per borrower, as hundredths of a percent. */ function setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { require(borrowers.length == newAllocations.length, 'LS1Admin: Params length mismatch'); require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBorrowerAllocations(borrowers, newAllocations); } function setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { _setBorrowingRestriction(borrower, isBorrowingRestricted); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Borrowing * @author dYdX * * @dev External functions for borrowers. See LS1BorrowerAllocations for details on * borrower accounting. */ abstract contract LS1Borrowing is LS1Staking, LS1BorrowerAllocations { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Borrowed( address indexed borrower, uint256 amount, uint256 newBorrowedBalance ); event RepaidBorrow( address indexed borrower, address sender, uint256 amount, uint256 newBorrowedBalance ); event RepaidDebt( address indexed borrower, address sender, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Borrow staked funds. * * @param amount The token amount to borrow. */ function borrow( uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot borrow zero'); address borrower = msg.sender; // Revert if the borrower is restricted. require(!_BORROWER_RESTRICTIONS_[borrower], 'LS1Borrowing: Restricted'); // Get contract available amount and revert if there is not enough to withdraw. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); require( amount <= totalAvailableForBorrow, 'LS1Borrowing: Amount > available' ); // Get new net borrow and revert if it is greater than the allocated balance for new borrowing. uint256 newBorrowedBalance = _BORROWED_BALANCES_[borrower].add(amount); require( newBorrowedBalance <= _getAllocatedBalanceForNewBorrowing(borrower), 'LS1Borrowing: Amount > allocated' ); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.add(amount); // Transfer token to the borrower. STAKED_TOKEN.safeTransfer(borrower, amount); emit Borrowed(borrower, amount, newBorrowedBalance); } /** * @notice Repay borrowed funds for the specified borrower. Reverts if repay amount exceeds * borrowed amount. * * @param borrower The borrower on whose behalf to make a repayment. * @param amount The amount to repay. */ function repayBorrow( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; require(amount <= oldBorrowedBalance, 'LS1Borrowing: Repay > borrowed'); uint256 newBorrowedBalance = oldBorrowedBalance.sub(amount); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidBorrow(borrower, msg.sender, amount, newBorrowedBalance); } /** * @notice Repay a debt amount owed by a borrower. * * @param borrower The borrower whose debt to repay. * @param amount The amount to repay. */ function repayDebt( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldDebtAmount = _BORROWER_DEBT_BALANCES_[borrower]; require(amount <= oldDebtAmount, 'LS1Borrowing: Repay > debt'); uint256 newDebtBalance = oldDebtAmount.sub(amount); // Update storage. _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_.add(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidDebt(borrower, msg.sender, amount, newDebtBalance); } /** * @notice Get the max additional amount that the borrower can borrow. * * @return The max additional amount that the borrower can borrow right now. */ function getBorrowableAmount( address borrower ) external view returns (uint256) { if (_BORROWER_RESTRICTIONS_[borrower]) { return 0; } // Get the remaining unused allocation for the borrower. uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; uint256 borrowerAllocatedBalance = _getAllocatedBalanceForNewBorrowing(borrower); if (borrowerAllocatedBalance <= oldBorrowedBalance) { return 0; } uint256 borrowerRemainingAllocatedBalance = borrowerAllocatedBalance.sub(oldBorrowedBalance); // Don't allow new borrowing to take out funds that are reserved for debt or inactive balances. // Typically, this will not be the limiting factor, but it can be. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); return Math.min(borrowerRemainingAllocatedBalance, totalAvailableForBorrow); } // ============ Public Functions ============ /** * @notice Get the funds currently available in the contract for borrowing. * * @return The amount of non-debt, non-inactive funds in the contract. */ function getContractBalanceAvailableToBorrow() public view returns (uint256) { uint256 availableStake = getContractBalanceAvailableToWithdraw(); uint256 inactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Note: The funds available to withdraw may be less than the inactive balance. if (availableStake <= inactiveBalance) { return 0; } return availableStake.sub(inactiveBalance); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; /** * @title LS1DebtAccounting * @author dYdX * * @dev Allows converting an overdue balance into "debt", which is accounted for separately from * the staked and borrowed balances. This allows the system to rebalance/restabilize itself in the * case where a borrower fails to return borrowed funds on time. * * The shortfall debt calculation is as follows: * * - Let A be the total active balance. * - Let B be the total borrowed balance. * - Let X be the total inactive balance. * - Then, a shortfall occurs if at any point B > A. * - The shortfall debt amount is `D = B - A` * - The borrowed balances are decreased by `B_new = B - D` * - The inactive balances are decreased by `X_new = X - D` * - The shortfall index is recorded as `Y = X_new / X` * - The borrower and staker debt balances are increased by `D` * * Note that `A + X >= B` (The active and inactive balances are at least the borrowed balance.) * This implies that `X >= D` (The inactive balance is always at least the shortfall debt.) */ abstract contract LS1DebtAccounting is LS1BorrowerAllocations { using SafeERC20 for IERC20; using SafeMath for uint256; using Math for uint256; // ============ Events ============ event ConvertedInactiveBalancesToDebt( uint256 shortfallAmount, uint256 shortfallIndex, uint256 newInactiveBalance ); event DebtMarked( address indexed borrower, uint256 amount, uint256 newBorrowedBalance, uint256 newDebtBalance ); // ============ External Functions ============ /** * @notice Restrict a borrower from borrowing. The borrower must have exceeded their borrowing * allocation. Can be called by anyone. * * Unlike markDebt(), this function can be called even if the contract in TOTAL is not insolvent. */ function restrictBorrower( address borrower ) external nonReentrant { require( isBorrowerOverdue(borrower), 'LS1DebtAccounting: Borrower not overdue' ); _setBorrowingRestriction(borrower, true); } /** * @notice Convert the shortfall amount between the active and borrowed balances into “debt.” * * The function determines the size of the debt, and then does the following: * - Assign the debt to borrowers, taking the same amount out of their borrowed balance. * - Impose borrow restrictions on borrowers to whom the debt was assigned. * - Socialize the loss pro-rata across inactive balances. Each balance with a loss receives * an equal amount of debt balance that can be withdrawn as debts are repaid. * * @param borrowers A list of borrowers who are responsible for the full shortfall amount. * * @return The shortfall debt amount. */ function markDebt( address[] calldata borrowers ) external nonReentrant returns (uint256) { // The debt is equal to the difference between the total active and total borrowed balances. uint256 totalActiveCurrent = getTotalActiveBalanceCurrentEpoch(); uint256 totalBorrowed = _TOTAL_BORROWED_BALANCE_; require(totalBorrowed > totalActiveCurrent, 'LS1DebtAccounting: No shortfall'); uint256 shortfallDebt = totalBorrowed.sub(totalActiveCurrent); // Attribute debt to borrowers. _attributeDebtToBorrowers(shortfallDebt, totalActiveCurrent, borrowers); // Apply the debt to inactive balances, moving the same amount into users debt balances. _convertInactiveBalanceToDebt(shortfallDebt); return shortfallDebt; } // ============ Public Functions ============ /** * @notice Whether the borrower is overdue on a payment, and is currently subject to having their * borrowing rights revoked. * * @param borrower The borrower to check. */ function isBorrowerOverdue( address borrower ) public view returns (bool) { uint256 allocatedBalance = getAllocatedBalanceCurrentEpoch(borrower); uint256 borrowedBalance = _BORROWED_BALANCES_[borrower]; return borrowedBalance > allocatedBalance; } // ============ Private Functions ============ /** * @dev Helper function to partially or fully convert inactive balances to debt. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. */ function _convertInactiveBalanceToDebt( uint256 shortfallDebt ) private { // Get the total inactive balance. uint256 oldInactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Calculate the index factor for the shortfall. uint256 newInactiveBalance = 0; uint256 shortfallIndex = 0; if (oldInactiveBalance > shortfallDebt) { newInactiveBalance = oldInactiveBalance.sub(shortfallDebt); shortfallIndex = SHORTFALL_INDEX_BASE.mul(newInactiveBalance).div(oldInactiveBalance); } // Get the shortfall amount applied to inactive balances. uint256 shortfallAmount = oldInactiveBalance.sub(newInactiveBalance); // Apply the loss. This moves the debt from stakers' inactive balances to their debt balances. _applyShortfall(shortfallAmount, shortfallIndex); emit ConvertedInactiveBalancesToDebt(shortfallAmount, shortfallIndex, newInactiveBalance); } /** * @dev Helper function to attribute debt to borrowers, adding it to their debt balances. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. * @param totalActiveCurrent The total active balance for the current epoch. * @param borrowers A list of borrowers responsible for the full shortfall amount. */ function _attributeDebtToBorrowers( uint256 shortfallDebt, uint256 totalActiveCurrent, address[] calldata borrowers ) private { // Find borrowers to attribute the total debt amount to. The sum of all borrower shortfalls is // always at least equal to the overall shortfall, so it is always possible to specify a list // of borrowers whose excess borrows cover the full shortfall amount. // // Denominate values in “points” scaled by TOTAL_ALLOCATION to avoid rounding. uint256 debtToBeAttributedPoints = shortfallDebt.mul(TOTAL_ALLOCATION); uint256 shortfallDebtAfterRounding = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 borrowedBalanceTokenAmount = _BORROWED_BALANCES_[borrower]; uint256 borrowedBalancePoints = borrowedBalanceTokenAmount.mul(TOTAL_ALLOCATION); uint256 allocationPoints = getAllocationFractionCurrentEpoch(borrower); uint256 allocatedBalancePoints = totalActiveCurrent.mul(allocationPoints); // Skip this borrower if they have not exceeded their allocation. if (borrowedBalancePoints <= allocatedBalancePoints) { continue; } // Calculate the borrower's debt, and limit to the remaining amount to be allocated. uint256 borrowerDebtPoints = borrowedBalancePoints.sub(allocatedBalancePoints); borrowerDebtPoints = Math.min(borrowerDebtPoints, debtToBeAttributedPoints); // Move the debt from the borrowers' borrowed balance to the debt balance. Rounding may occur // when converting from “points” to tokens. We round up to ensure the final borrowed balance // is not greater than the allocated balance. uint256 borrowerDebtTokenAmount = borrowerDebtPoints.divRoundUp(TOTAL_ALLOCATION); uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].add(borrowerDebtTokenAmount); uint256 newBorrowedBalance = borrowedBalanceTokenAmount.sub(borrowerDebtTokenAmount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _BORROWED_BALANCES_[borrower] = newBorrowedBalance; emit DebtMarked(borrower, borrowerDebtTokenAmount, newBorrowedBalance, newDebtBalance); shortfallDebtAfterRounding = shortfallDebtAfterRounding.add(borrowerDebtTokenAmount); // Restrict the borrower from further borrowing. _setBorrowingRestriction(borrower, true); // Update the remaining amount to allocate. debtToBeAttributedPoints = debtToBeAttributedPoints.sub(borrowerDebtPoints); // Exit early if all debt was allocated. if (debtToBeAttributedPoints == 0) { break; } } // Require the borrowers to cover the full debt amount. This should always be possible. require( debtToBeAttributedPoints == 0, 'LS1DebtAccounting: Borrowers do not cover the shortfall' ); // Move the debt from the total borrowed balance to the total debt balance. _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(shortfallDebtAfterRounding); _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.add(shortfallDebtAfterRounding); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Allows a user with an active stake to transfer their * staked tokens to another user, even if they would otherwise be restricted from withdrawing. */ abstract contract LS1ERC20 is LS1StakedBalances, IERC20Detailed { using SafeMath for uint256; // ============ External Functions ============ function name() external pure override returns (string memory) { return 'dYdX Staked USDC'; } function symbol() external pure override returns (string memory) { return 'stkUSDC'; } function decimals() external pure override returns (uint8) { return 6; } /** * @notice Get the total supply of `STAKED_TOKEN` staked to the contract. * This value is calculated from adding the active + inactive balances of * this current epoch. * * @return The total staked balance of this contract. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get the current balance of `STAKED_TOKEN` the user has staked to the contract. * This value includes the users active + inactive balances, but note that only * their active balance in the next epoch is transferable. * * @param account The account to get the balance of. * * @return The user's balance. */ function balanceOf( address account ) external view override returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'LS1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'LS1ERC20: Decreased allowance below zero' ) ); return true; } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'LS1ERC20: Transfer from address(0)'); require(recipient != address(0), 'LS1ERC20: Transfer to address(0)'); require( getTransferableBalance(sender) >= amount, 'LS1ERC20: Transfer exceeds next epoch active balance' ); _transferCurrentAndNextActiveBalance(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'LS1ERC20: Approve from address(0)'); require(spender != address(0), 'LS1ERC20: Approve to address(0)'); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Failsafe * @author dYdX * * @dev Functions for recovering from very unlikely edge cases. */ abstract contract LS1Failsafe is LS1StakedBalances { using SafeCast for uint256; using SafeMath for uint256; /** * @notice Settle the sender's inactive balance up to the specified epoch. This allows the * balance to be settled while putting an upper bound on the gas expenditure per function call. * This is unlikely to be needed in practice. * * @param maxEpoch The epoch to settle the sender's inactive balance up to. */ function failsafeSettleUserInactiveBalanceToEpoch( uint256 maxEpoch ) external nonReentrant { address staker = msg.sender; _failsafeSettleUserInactiveBalance(staker, maxEpoch); } /** * @notice Sets the sender's inactive balance to zero. This allows for recovery from a situation * where the gas cost to settle the balance is higher than the value of the balance itself. * We provide this function as an alternative to settlement, since the gas cost for settling an * inactive balance is unbounded (except in that it may grow at most linearly with the number of * epochs that have passed). */ function failsafeDeleteUserInactiveBalance() external nonReentrant { address staker = msg.sender; _failsafeDeleteUserInactiveBalance(staker); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are three types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. * * DEBT_OPERATOR_ROLE: * * This operator is allowed to decrease staker and borrower debt balances. Typically, each change * to a staker debt balance should be offset by a corresponding change in a borrower debt * balance, but this is not strictly required. This role could used by a smart contract to * tokenize debt balances or to provide a pro-rata distribution to debt holders, for example. */ abstract contract LS1Operators is LS1Staking { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); event OperatorDecreasedStakerDebt( address indexed staker, uint256 amount, uint256 newDebtBalance, address operator ); event OperatorDecreasedBorrowerDebt( address indexed borrower, uint256 amount, uint256 newDebtBalance, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, amount); emit OperatorWithdrawalRequestedFor(staker, amount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, amount); emit OperatorWithdrewStakeFor(staker, recipient, amount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } /** * @notice Decreased the balance recording debt owed to a staker. * * @param staker The staker whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseStakerDebt( address staker, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 oldDebtBalance = _settleStakerDebtBalance(staker); uint256 newDebtBalance = oldDebtBalance.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit OperatorDecreasedStakerDebt(staker, amount, newDebtBalance, msg.sender); return newDebtBalance; } /** * @notice Decreased the balance recording debt owed by a borrower. * * @param borrower The borrower whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseBorrowerDebt( address borrower, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].sub(amount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); emit OperatorDecreasedBorrowerDebt(borrower, amount, newDebtBalance, msg.sender); return newDebtBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title SafeCast * @author dYdX * * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require(uint256(b) == a, 'SafeCast: toUint16 overflow'); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require(uint256(b) == a, 'SafeCast: toUint32 overflow'); return b; } /** * @dev Downcast to a uint112, reverting on overflow. */ function toUint112( uint256 a ) internal pure returns (uint112) { uint112 b = uint112(a); require(uint256(b) == a, 'SafeCast: toUint112 overflow'); return b; } /** * @dev Downcast to a uint120, reverting on overflow. */ function toUint120( uint256 a ) internal pure returns (uint120) { uint120 b = uint120(a); require(uint256(b) == a, 'SafeCast: toUint120 overflow'); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require(uint256(b) == a, 'SafeCast: toUint128 overflow'); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require(uint256(b) == a, 'SafeCast: toUint224 overflow'); return b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1BorrowerAllocations * @author dYdX * * @dev Gives a set of addresses permission to withdraw staked funds. * * The amount that can be withdrawn depends on a borrower's allocation percentage and the total * available funds. Both the allocated percentage and total available funds can change, at * predefined times specified by LS1EpochSchedule. * * If a borrower's borrowed balance is greater than their allocation at the start of the next epoch * then they are expected and trusted to return the difference before the start of that epoch. */ abstract contract LS1BorrowerAllocations is LS1StakedBalances { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The total units to be allocated. uint256 public constant TOTAL_ALLOCATION = 1e4; // ============ Events ============ event ScheduledBorrowerAllocationChange( address indexed borrower, uint256 oldAllocation, uint256 newAllocation, uint256 epochNumber ); event BorrowingRestrictionChanged( address indexed borrower, bool isBorrowingRestricted ); // ============ Initializer ============ function __LS1BorrowerAllocations_init() internal { _BORROWER_ALLOCATIONS_[address(0)] = LS1Types.StoredAllocation({ currentEpoch: 0, currentEpochAllocation: TOTAL_ALLOCATION.toUint120(), nextEpochAllocation: TOTAL_ALLOCATION.toUint120() }); } // ============ Public Functions ============ /** * @notice Get the borrower allocation for the current epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's current allocation in hundreds of a percent. */ function getAllocationFractionCurrentEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).currentEpochAllocation); } /** * @notice Get the borrower allocation for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's next allocation in hundreds of a percent. */ function getAllocationFractionNextEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).nextEpochAllocation); } /** * @notice Get the allocated borrowable token balance of a borrower for the current epoch. * * This is the amount which a borrower can be penalized for exceeding. * * @param borrower The borrower to get the allocation for. * * @return The token amount allocated to the borrower for the current epoch. */ function getAllocatedBalanceCurrentEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionCurrentEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceCurrentEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } /** * @notice Preview the allocated balance of a borrower for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The anticipated token amount allocated to the borrower for the next epoch. */ function getAllocatedBalanceNextEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionNextEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceNextEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Internal Functions ============ /** * @dev Change the allocations of certain borrowers. */ function _setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) internal { // These must net out so that the total allocation is unchanged. uint256 oldAllocationSum = 0; uint256 newAllocationSum = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 newAllocation = newAllocations[i]; // Get the old allocation. LS1Types.StoredAllocation memory allocationStruct = _loadBorrowerAllocation(borrower); uint256 oldAllocation = uint256(allocationStruct.currentEpochAllocation); // Update the borrower's next allocation. allocationStruct.nextEpochAllocation = newAllocation.toUint120(); // If epoch zero hasn't started, update current allocation as well. uint256 epochNumber = 0; if (hasEpochZeroStarted()) { epochNumber = uint256(allocationStruct.currentEpoch).add(1); } else { allocationStruct.currentEpochAllocation = newAllocation.toUint120(); } // Commit the new allocation. _BORROWER_ALLOCATIONS_[borrower] = allocationStruct; emit ScheduledBorrowerAllocationChange(borrower, oldAllocation, newAllocation, epochNumber); // Record totals. oldAllocationSum = oldAllocationSum.add(oldAllocation); newAllocationSum = newAllocationSum.add(newAllocation); } // Require the total allocated units to be unchanged. require( oldAllocationSum == newAllocationSum, 'LS1BorrowerAllocations: Invalid' ); } /** * @dev Restrict a borrower from further borrowing. */ function _setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) internal { bool oldIsBorrowingRestricted = _BORROWER_RESTRICTIONS_[borrower]; if (oldIsBorrowingRestricted != isBorrowingRestricted) { _BORROWER_RESTRICTIONS_[borrower] = isBorrowingRestricted; emit BorrowingRestrictionChanged(borrower, isBorrowingRestricted); } } /** * @dev Get the allocated balance that the borrower can make use of for new borrowing. * * @return The amount that the borrower can borrow up to. */ function _getAllocatedBalanceForNewBorrowing( address borrower ) internal view returns (uint256) { // Use the smaller of the current and next allocation fractions, since if a borrower's // allocation was just decreased, we should take that into account in limiting new borrows. uint256 currentAllocation = getAllocationFractionCurrentEpoch(borrower); uint256 nextAllocation = getAllocationFractionNextEpoch(borrower); uint256 allocation = Math.min(currentAllocation, nextAllocation); // If we are in the blackout window, use the next active balance. Otherwise, use current. // Note that the next active balance is never greater than the current active balance. uint256 availableTokens; if (inBlackoutWindow()) { availableTokens = getTotalActiveBalanceNextEpoch(); } else { availableTokens = getTotalActiveBalanceCurrentEpoch(); } return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Private Functions ============ function _loadBorrowerAllocation( address borrower ) private view returns (LS1Types.StoredAllocation memory) { LS1Types.StoredAllocation memory allocation = _BORROWER_ALLOCATIONS_[borrower]; // Ignore rollover logic before epoch zero. if (hasEpochZeroStarted()) { uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(allocation.currentEpoch)) { // Roll the allocation forward. allocation.currentEpoch = currentEpoch.toUint16(); allocation.currentEpochAllocation = allocation.nextEpochAllocation; } } return allocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1ERC20 } from './LS1ERC20.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Staking * @author dYdX * * @dev External functions for stakers. See LS1StakedBalances for details on staker accounting. */ abstract contract LS1Staking is LS1StakedBalances, LS1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 amount ); event WithdrawalRequested( address indexed staker, uint256 amount ); event WithdrewStake( address indexed staker, address recipient, uint256 amount ); event WithdrewDebt( address indexed staker, address recipient, uint256 amount, uint256 newDebtBalance ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param amount The amount to stake. */ function stake( uint256 amount ) external nonReentrant { _stake(msg.sender, amount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param amount The amount to stake. */ function stakeFor( address staker, uint256 amount ) external nonReentrant { _stake(staker, amount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawal( uint256 amount ) external nonReentrant { _requestWithdrawal(msg.sender, amount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 amount ) external nonReentrant { _withdrawStake(msg.sender, recipient, amount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, amount); return amount; } /** * @notice Withdraw a debt amount owed to the sender, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The token amount to withdraw from the sender's debt balance. */ function withdrawDebt( address recipient, uint256 amount ) external nonReentrant { _withdrawDebt(msg.sender, recipient, amount); } /** * @notice Withdraw the max available debt amount. * * This is less gas-efficient than querying the max via eth_call and calling withdrawDebt(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxDebt( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getDebtAvailableToWithdraw(msg.sender); _withdrawDebt(msg.sender, recipient, amount); return amount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available to withdraw taking into account the contract balance. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. uint256 stakerBalance = getInactiveBalanceCurrentEpoch(staker); uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); return Math.min(stakerBalance, totalStakeAvailable); } /** * @notice Get the funds currently available in the contract for staker withdrawals. * * @return The amount of non-debt funds in the contract. */ function getContractBalanceAvailableToWithdraw() public view returns (uint256) { uint256 contractBalance = STAKED_TOKEN.balanceOf(address(this)); uint256 availableDebtBalance = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return contractBalance.sub(availableDebtBalance); // Should never underflow. } /** * @notice Get the amount of debt available to withdraw. * * @param staker The address whose balance to check. * * @return The debt amount that can be withdrawn. */ function getDebtAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that `totalDebtAvailable` should never be less than the contract token balance. uint256 stakerDebtBalance = getStakerDebtBalance(staker); uint256 totalDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return Math.min(stakerDebtBalance, totalDebtAvailable); } // ============ Internal Functions ============ function _stake( address staker, uint256 amount ) internal { // Increase current and next active balance. _increaseCurrentAndNextActiveBalance(staker, amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit Staked(staker, msg.sender, amount); emit Transfer(address(0), msg.sender, amount); } function _requestWithdrawal( address staker, uint256 amount ) internal { require( !inBlackoutWindow(), 'LS1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( amount <= requestableBalance, 'LS1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, amount); emit WithdrawalRequested(staker, amount); } function _withdrawStake( address staker, address recipient, uint256 amount ) internal { // Get contract available amount and revert if there is not enough to withdraw. uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); require( amount <= totalStakeAvailable, 'LS1Staking: Withdraw exceeds amount available in the contract' ); // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( amount <= withdrawableBalance, 'LS1Staking: Withdraw exceeds inactive balance' ); // Decrease the staker's current and next inactive balance. Reverts if balance is insufficient. _decreaseCurrentAndNextInactiveBalance(staker, amount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit Transfer(msg.sender, address(0), amount); emit WithdrewStake(staker, recipient, amount); } // ============ Private Functions ============ function _withdrawDebt( address staker, address recipient, uint256 amount ) private { // Get old amounts and revert if there is not enough to withdraw. uint256 oldDebtBalance = _settleStakerDebtBalance(staker); require( amount <= oldDebtBalance, 'LS1Staking: Withdraw debt exceeds debt owed' ); uint256 oldDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; require( amount <= oldDebtAvailable, 'LS1Staking: Withdraw debt exceeds amount available' ); // Caculate updated amounts and update storage. uint256 newDebtBalance = oldDebtBalance.sub(amount); uint256 newDebtAvailable = oldDebtAvailable.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = newDebtAvailable; // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit WithdrewDebt(staker, recipient, amount, newDebtBalance); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.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 Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Rewards } from './LS1Rewards.sol'; /** * @title LS1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Internal functions may revert if epoch zero has not started. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Available for borrowing; earning staking rewards; cannot be withdrawn by staker. * - inactive: Unavailable for borrowing; does not earn rewards; can be withdrawn by the staker. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. Also, inactive user balances make use of the shortfallCounter field as * described below. * * INACTIVE BALANCE ACCOUNTING: * * Inactive funds may be subject to pro-rata socialized losses in the event of a shortfall where * a borrower is late to pay back funds that have been requested for withdrawal. We track losses * via indexes. Each index represents the fraction of inactive funds that were converted into * debt during a given shortfall event. Each staker inactive balance stores a cached shortfall * counter, representing the number of shortfalls that occurred in the past relative to when the * balance was last updated. * * Any losses incurred by an inactive balance translate into an equal credit to that staker's * debt balance. See LS1DebtAccounting for more info about how the index is calculated. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via LS1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards or debt balances. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract LS1StakedBalances is LS1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ uint256 internal constant SHORTFALL_INDEX_BASE = 1e36; // ============ Events ============ event ReceivedDebt( address indexed staker, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get a staker's debt balance, after accounting for unsettled shortfalls. * Note that this does not modify _STAKER_DEBT_BALANCES_, so the debt balance must still be * settled before it can be withdrawn. * * @param staker The staker to get the balance of. * * @return The settled debt balance. */ function getStakerDebtBalance( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (, uint256 newDebtAmount) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return _STAKER_DEBT_BALANCES_[staker].add(newDebtAmount); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleStakerDebtBalance( address staker ) internal returns (uint256) { // Settle the inactive balance to settle any new debt. _settleBalance(staker, false); // Return the settled debt balance. return _STAKER_DEBT_BALANCES_[staker]; } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } function _applyShortfall( uint256 shortfallAmount, uint256 shortfallIndex ) internal { // Decrease the total inactive balance. _decreaseCurrentAndNextBalances(address(0), false, shortfallAmount); _SHORTFALLS_.push(LS1Types.Shortfall({ epoch: getCurrentEpoch().toUint16(), index: shortfallIndex.toUint224() })); } /** * @dev Does the same thing as _settleBalance() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeSettleUserInactiveBalance( address staker, uint256 maxEpoch ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = _failsafeLoadUserInactiveBalanceForUpdate(balancePtr, staker, maxEpoch); _storeBalance(balancePtr, balance); } /** * @dev Sets the user inactive balance to zero. See LS1Failsafe. * * Since the balance will never be settled, the staker loses any debt balance that they would * have otherwise been entitled to from shortfall losses. * * Also note that we don't update the total inactive balance, but this is fine. */ function _failsafeDeleteUserInactiveBalance( address staker ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = LS1Types.StoredBalance({ currentEpoch: 0, currentEpochBalance: 0, nextEpochBalance: 0, shortfallCounter: 0 }); _storeBalance(balancePtr, balance); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (LS1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function modifies state, and so the balance MUST be stored afterwards. * - For active balances: if a rollover occurs, rewards are settled to the epoch boundary. * - For inactive user balances: if a shortfall occurs, the user's debt balance is increased. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (LS1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( LS1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Total inactive balance. if (maybeStaker == address(0)) { return _loadTotalInactiveBalance(balancePtr); } // User inactive balance. (LS1Types.StoredBalance memory balance, uint256 newStakerDebt) = _loadUserInactiveBalance(balancePtr); if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[maybeStaker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[maybeStaker] = newDebtBalance; emit ReceivedDebt(maybeStaker, newStakerDebt, newDebtBalance); } return balance; } function _loadActiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns ( LS1Types.StoredBalance memory, uint256, uint256, bool ) { LS1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadTotalInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } function _loadUserInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory, uint256) { LS1Types.StoredBalance memory balance = balancePtr; uint256 currentEpoch = getCurrentEpoch(); // If there is no non-zero balance, sync the epoch number and shortfall counter and exit. // Note: Next inactive balance is always >= current, so we only need to check next. if (balance.nextEpochBalance == 0) { balance.currentEpoch = currentEpoch.toUint16(); balance.shortfallCounter = _SHORTFALLS_.length.toUint16(); return (balance, 0); } // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } return (balance, newStakerDebt); } function _applyShortfallsToBalance( LS1Types.StoredBalance memory balance ) private view returns (LS1Types.StoredBalance memory, uint256) { // Get the cached and global shortfall counters. uint256 shortfallCounter = uint256(balance.shortfallCounter); uint256 globalShortfallCounter = _SHORTFALLS_.length; // If the counters are in sync, then there is nothing to do. if (shortfallCounter == globalShortfallCounter) { return (balance, 0); } // Get the balance params. uint16 cachedEpoch = balance.currentEpoch; uint256 oldCurrentBalance = uint256(balance.currentEpochBalance); // Calculate the new balance after applying shortfalls. // // Note: In theory, this while-loop may render an account's funds inaccessible if there are // too many shortfalls, and too much gas is required to apply them all. This is very unlikely // to occur in practice, but we provide _failsafeLoadUserInactiveBalance() just in case to // ensure recovery is possible. uint256 newCurrentBalance = oldCurrentBalance; while (shortfallCounter < globalShortfallCounter) { LS1Types.Shortfall memory shortfall = _SHORTFALLS_[shortfallCounter]; // Stop applying shortfalls if they are in the future relative to the balance current epoch. if (shortfall.epoch > cachedEpoch) { break; } // Update the current balance to reflect the shortfall. uint256 shortfallIndex = uint256(shortfall.index); newCurrentBalance = newCurrentBalance.mul(shortfallIndex).div(SHORTFALL_INDEX_BASE); // Increment the staker's shortfall counter. shortfallCounter = shortfallCounter.add(1); } // Calculate the loss. // If the loaded balance is stored, this amount must be added to the staker's debt balance. uint256 newStakerDebt = oldCurrentBalance.sub(newCurrentBalance); // Update the balance. balance.currentEpochBalance = newCurrentBalance.toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(newStakerDebt).toUint112(); balance.shortfallCounter = shortfallCounter.toUint16(); return (balance, newStakerDebt); } /** * @dev Store a balance. */ function _storeBalance( LS1Types.StoredBalance storage balancePtr, LS1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; balancePtr.shortfallCounter = balance.shortfallCounter; } /** * @dev Does the same thing as _loadBalanceForUpdate() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeLoadUserInactiveBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address staker, uint256 maxEpoch ) private returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Validate maxEpoch. uint256 currentEpoch = getCurrentEpoch(); uint256 cachedEpoch = uint256(balance.currentEpoch); require( maxEpoch >= cachedEpoch && maxEpoch <= currentEpoch, 'LS1StakedBalances: maxEpoch' ); // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (maxEpoch > cachedEpoch) { balance.currentEpoch = maxEpoch.toUint16(); // Use maxEpoch instead of currentEpoch. balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } // Apply debt if needed. if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[staker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit ReceivedDebt(staker, newStakerDebt, newDebtBalance); } return balance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1EpochSchedule } from './LS1EpochSchedule.sol'; /** * @title LS1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract LS1Rewards is LS1EpochSchedule { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require(distributionEnd >= distributionStart, 'LS1Rewards: Invalid parameters'); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __LS1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Roles } from './LS1Roles.sol'; /** * @title LS1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract LS1EpochSchedule is LS1Roles { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Minimum blackout window. Note: The min epoch length is twice the current blackout window. uint256 private constant MIN_BLACKOUT_WINDOW = 3 days; /// @dev Maximum epoch length. Note: The max blackout window is half the current epoch length. uint256 private constant MAX_EPOCH_LENGTH = 92 days; // Approximately one quarter year. // ============ Events ============ event EpochParametersChanged( LS1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __LS1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'LS1EpochSchedule: Epoch zero must be in future' ); // Don't use _setBlackoutWindow() since the interval is not set yet and validation would fail. _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { _validateParamLengths(interval, _BLACKOUT_WINDOW_); LS1Types.EpochParameters memory epochParameters = LS1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _validateParamLengths(uint256(_EPOCH_PARAMETERS_.interval), blackoutWindow); _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The length of an epoch, in seconds. * @return The start of epoch zero, in seconds. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require(block.timestamp >= offset, 'LS1EpochSchedule: Epoch zero has not started'); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } /** * @dev Helper for common validation: verify that the interval and window lengths are valid. */ function _validateParamLengths( uint256 interval, uint256 blackoutWindow ) private pure { require( blackoutWindow.mul(2) <= interval, 'LS1EpochSchedule: Blackout window can be at most half the epoch length' ); require( blackoutWindow >= MIN_BLACKOUT_WINDOW, 'LS1EpochSchedule: Blackout window too large' ); require( interval <= MAX_EPOCH_LENGTH, 'LS1EpochSchedule: Epoch length too small' ); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Roles * @author dYdX * * @dev Defines roles used in the LiquidityStakingV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove users from any of the below roles it manages. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- BORROWER_ADMIN_ROLE * | -> May set borrower allocations and allow/restrict borrowers from borrowing. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * | -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). * | * +-- DEBT_OPERATOR_ROLE * -> May decrease borrow debt and decrease staker debt. */ abstract contract LS1Roles is LS1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant BORROWER_ADMIN_ROLE = keccak256('BORROWER_ADMIN_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); bytes32 public constant DEBT_OPERATOR_ROLE = keccak256('DEBT_OPERATOR_ROLE'); function __LS1Roles_init() internal { // Assign roles to the sender. // // The DEBT_OPERATOR_ROLE, STAKE_OPERATOR_ROLE, and CLAIM_OPERATOR_ROLE roles are not // initially assigned. These can be assigned to other smart contracts to provide additional // functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); _setupRole(BORROWER_ADMIN_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(BORROWER_ADMIN_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(DEBT_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
Get old amounts and revert if there is not enough to withdraw. Caculate updated amounts and update storage. Transfer token to the recipient.
function _withdrawDebt( address staker, address recipient, uint256 amount ) private { uint256 oldDebtBalance = _settleStakerDebtBalance(staker); require( amount <= oldDebtBalance, 'LS1Staking: Withdraw debt exceeds debt owed' ); uint256 oldDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; require( amount <= oldDebtAvailable, 'LS1Staking: Withdraw debt exceeds amount available' ); uint256 newDebtBalance = oldDebtBalance.sub(amount); uint256 newDebtAvailable = oldDebtAvailable.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = newDebtAvailable; STAKED_TOKEN.safeTransfer(recipient, amount); emit WithdrewDebt(staker, recipient, amount, newDebtBalance); }
5,860,506
pragma solidity 0.5.11; library SafeMath { function ADD640(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB596(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB596(a, b, "SafeMath: subtraction overflow"); } function SUB596(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL119(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV27(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV27(a, b, "SafeMath: division by zero"); } function DIV27(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD463(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD463(a, b, "SafeMath: modulo by zero"); } function MOD463(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract InscribableToken { mapping(bytes32 => bytes32) public properties; event CLASSPROPERTYSET751( //inject NONSTANDARD NAMING bytes32 indexed key, bytes32 value ); event TOKENPROPERTYSET338( //inject NONSTANDARD NAMING uint indexed id, bytes32 indexed key, bytes32 value ); function _SETPROPERTY292( //inject NONSTANDARD NAMING uint _id, bytes32 _key, bytes32 _value ) internal { properties[GETTOKENKEY33(_id, _key)] = _value; emit TOKENPROPERTYSET338(_id, _key, _value); } function GETPROPERTY470( //inject NONSTANDARD NAMING uint _id, bytes32 _key ) public view returns (bytes32 _value) { return properties[GETTOKENKEY33(_id, _key)]; } function _SETCLASSPROPERTY718( //inject NONSTANDARD NAMING bytes32 _key, bytes32 _value ) internal { emit CLASSPROPERTYSET751(_key, _value); properties[GETCLASSKEY628(_key)] = _value; } function GETTOKENKEY33( //inject NONSTANDARD NAMING uint _tokenId, bytes32 _key ) public pure returns (bytes32) { // one prefix to prevent collisions return keccak256(abi.encodePacked(uint(1), _tokenId, _key)); } function GETCLASSKEY628(bytes32 _key) //inject NONSTANDARD NAMING public pure returns (bytes32) { // zero prefix to prevent collisions return keccak256(abi.encodePacked(uint(0), _key)); } function GETCLASSPROPERTY691(bytes32 _key) //inject NONSTANDARD NAMING public view returns (bytes32) { return properties[GETCLASSKEY628(_key)]; } } library String { function FROMUINT947(uint256 value) internal pure returns (string memory) { //inject NONSTANDARD NAMING if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } bytes constant alphabet572 = "0123456789abcdef"; //inject NONSTANDARD NAMING function FROMADDRESS777(address _addr) internal pure returns(string memory) { //inject NONSTANDARD NAMING bytes32 value = bytes32(uint256(_addr)); bytes memory str = new bytes(42); str[0] = '0'; str[1] = 'x'; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet572[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet572[uint(uint8(value[i + 12] & 0x0F))]; } return string(str); } } // solium-disable security/no-inline-assembly library StorageWrite { using SafeMath for uint256; function _GETSTORAGEARRAYSLOT595(uint _dest, uint _index) internal view returns (uint result) { //inject NONSTANDARD NAMING uint slot = _GETARRAYSLOT364(_dest, _index); assembly { result := sload(slot) } } function _GETARRAYSLOT364(uint _dest, uint _index) internal pure returns (uint slot) { //inject NONSTANDARD NAMING assembly { let free := mload(0x40) mstore(free, _dest) slot := add(keccak256(free, 32), _index) } } function _SETARRAYSLOT66(uint _dest, uint _index, uint _value) internal { //inject NONSTANDARD NAMING uint slot = _GETARRAYSLOT364(_dest, _index); assembly { sstore(slot, _value) } } function _LOADSLOTS761( //inject NONSTANDARD NAMING uint _slot, uint _offset, uint _perSlot, uint _length ) internal view returns (uint[] memory slots) { uint slotCount = _SLOTCOUNT226(_offset, _perSlot, _length); slots = new uint[](slotCount); // top and tail the slots uint firstPos = _POS762(_offset, _perSlot); // _offset.div(_perSlot); slots[0] = _GETSTORAGEARRAYSLOT595(_slot, firstPos); if (slotCount > 1) { uint lastPos = _POS762(_offset.ADD640(_length), _perSlot); // .div(_perSlot); slots[slotCount-1] = _GETSTORAGEARRAYSLOT595(_slot, lastPos); } } function _POS762(uint items, uint perPage) internal pure returns (uint) { //inject NONSTANDARD NAMING return items / perPage; } function _SLOTCOUNT226(uint _offset, uint _perSlot, uint _length) internal pure returns (uint) { //inject NONSTANDARD NAMING uint start = _offset / _perSlot; uint end = (_offset + _length) / _perSlot; return (end - start) + 1; } function _SAVESLOTS992(uint _slot, uint _offset, uint _size, uint[] memory _slots) internal { //inject NONSTANDARD NAMING uint offset = _offset.DIV27((256/_size)); for (uint i = 0; i < _slots.length; i++) { _SETARRAYSLOT66(_slot, offset + i, _slots[i]); } } function _WRITE724(uint[] memory _slots, uint _offset, uint _size, uint _index, uint _value) internal pure { //inject NONSTANDARD NAMING uint perSlot = 256 / _size; uint initialOffset = _offset % perSlot; uint slotPosition = (initialOffset + _index) / perSlot; uint withinSlot = ((_index + _offset) % perSlot) * _size; // evil bit shifting magic for (uint q = 0; q < _size; q += 8) { _slots[slotPosition] |= ((_value >> q) & 0xFF) << (withinSlot + q); } } function REPEATUINT16794(uint _slot, uint _offset, uint _length, uint16 _item) internal { //inject NONSTANDARD NAMING uint[] memory slots = _LOADSLOTS761(_slot, _offset, 16, _length); for (uint i = 0; i < _length; i++) { _WRITE724(slots, _offset, 16, i, _item); } _SAVESLOTS992(_slot, _offset, 16, slots); } function UINT16S436(uint _slot, uint _offset, uint16[] memory _items) internal { //inject NONSTANDARD NAMING uint[] memory slots = _LOADSLOTS761(_slot, _offset, 16, _items.length); for (uint i = 0; i < _items.length; i++) { _WRITE724(slots, _offset, 16, i, _items[i]); } _SAVESLOTS992(_slot, _offset, 16, slots); } function UINT8S318(uint _slot, uint _offset, uint8[] memory _items) internal { //inject NONSTANDARD NAMING uint[] memory slots = _LOADSLOTS761(_slot, _offset, 32, _items.length); for (uint i = 0; i < _items.length; i++) { _WRITE724(slots, _offset, 8, i, _items[i]); } _SAVESLOTS992(_slot, _offset, 8, slots); } } contract ImmutableToken { string public constant baseuri257 = "https://api.immutable.com/asset/"; //inject NONSTANDARD NAMING function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING return string(abi.encodePacked( baseuri257, String.FROMADDRESS777(address(this)), "/", String.FROMUINT947(tokenId) )); } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER48() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA774() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC165 { function SUPPORTSINTERFACE367(bytes4 interfaceId) external view returns (bool); //inject NONSTANDARD NAMING } contract ERC165 is IERC165 { bytes4 private constant _interface_id_erc165383 = 0x01ffc9a7; //inject NONSTANDARD NAMING mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _REGISTERINTERFACE770(_interface_id_erc165383); } function SUPPORTSINTERFACE367(bytes4 interfaceId) external view returns (bool) { //inject NONSTANDARD NAMING return _supportedInterfaces[interfaceId]; } function _REGISTERINTERFACE770(bytes4 interfaceId) internal { //inject NONSTANDARD NAMING require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } contract IERC721Receiver { function ONERC721RECEIVED640(address operator, address from, uint256 tokenId, bytes memory data) //inject NONSTANDARD NAMING public returns (bytes4); } library Address { function ISCONTRACT794(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE665(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE550(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library 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 CURRENT711(Counter storage counter) internal view returns (uint256) { //inject NONSTANDARD NAMING return counter._value; } function INCREMENT113(Counter storage counter) internal { //inject NONSTANDARD NAMING counter._value += 1; } function DECREMENT390(Counter storage counter) internal { //inject NONSTANDARD NAMING counter._value = counter._value.SUB596(1); } } contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED114(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER48(); emit OWNERSHIPTRANSFERRED114(address(0), _owner); } function OWNER177() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER453() { //inject NONSTANDARD NAMING require(ISOWNER434(), "Ownable: caller is not the owner"); _; } function ISOWNER434() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER48() == _owner; } function RENOUNCEOWNERSHIP876() public ONLYOWNER453 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED114(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP194(address newOwner) public ONLYOWNER453 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP3(newOwner); } function _TRANSFEROWNERSHIP3(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED114(_owner, newOwner); _owner = newOwner; } } contract IERC721 is IERC165 { event TRANSFER336(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVAL97(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL640(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING function BALANCEOF188(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function OWNEROF127(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function SAFETRANSFERFROM19(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function TRANSFERFROM301(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function APPROVE921(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function GETAPPROVED252(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING function SETAPPROVALFORALL542(address operator, bool _approved) public; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL999(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING function SAFETRANSFERFROM19(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING } contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _erc721_received341 = 0x150b7a02; //inject NONSTANDARD NAMING // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _interface_id_erc721248 = 0x80ac58cd; //inject NONSTANDARD NAMING constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE770(_interface_id_erc721248); } function BALANCEOF188(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].CURRENT711(); } function OWNEROF127(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function APPROVE921(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING address owner = OWNEROF127(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_MSGSENDER48() == owner || ISAPPROVEDFORALL999(owner, _MSGSENDER48()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit APPROVAL97(owner, to, tokenId); } function GETAPPROVED252(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING require(_EXISTS289(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function SETAPPROVALFORALL542(address to, bool approved) public { //inject NONSTANDARD NAMING require(to != _MSGSENDER48(), "ERC721: approve to caller"); _operatorApprovals[_MSGSENDER48()][to] = approved; emit APPROVALFORALL640(_MSGSENDER48(), to, approved); } function ISAPPROVEDFORALL999(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING return _operatorApprovals[owner][operator]; } function TRANSFERFROM301(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING //solhint-disable-next-line max-line-length require(_ISAPPROVEDOROWNER149(_MSGSENDER48(), tokenId), "ERC721: transfer caller is not owner nor approved"); _TRANSFERFROM539(from, to, tokenId); } function SAFETRANSFERFROM19(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING SAFETRANSFERFROM19(from, to, tokenId, ""); } function SAFETRANSFERFROM19(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING require(_ISAPPROVEDOROWNER149(_MSGSENDER48(), tokenId), "ERC721: transfer caller is not owner nor approved"); _SAFETRANSFERFROM254(from, to, tokenId, _data); } function _SAFETRANSFERFROM254(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _TRANSFERFROM539(from, to, tokenId); require(_CHECKONERC721RECEIVED206(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _EXISTS289(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; return owner != address(0); } function _ISAPPROVEDOROWNER149(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING require(_EXISTS289(tokenId), "ERC721: operator query for nonexistent token"); address owner = OWNEROF127(tokenId); return (spender == owner || GETAPPROVED252(tokenId) == spender || ISAPPROVEDFORALL999(owner, spender)); } function _SAFEMINT5(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING _SAFEMINT5(to, tokenId, ""); } function _SAFEMINT5(address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _MINT330(to, tokenId); require(_CHECKONERC721RECEIVED206(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _MINT330(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(to != address(0), "ERC721: mint to the zero address"); require(!_EXISTS289(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].INCREMENT113(); emit TRANSFER336(address(0), to, tokenId); } function _BURN121(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF127(tokenId) == owner, "ERC721: burn of token that is not own"); _CLEARAPPROVAL340(tokenId); _ownedTokensCount[owner].DECREMENT390(); _tokenOwner[tokenId] = address(0); emit TRANSFER336(owner, address(0), tokenId); } function _BURN121(uint256 tokenId) internal { //inject NONSTANDARD NAMING _BURN121(OWNEROF127(tokenId), tokenId); } function _TRANSFERFROM539(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF127(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _CLEARAPPROVAL340(tokenId); _ownedTokensCount[from].DECREMENT390(); _ownedTokensCount[to].INCREMENT113(); _tokenOwner[tokenId] = to; emit TRANSFER336(from, to, tokenId); } function _CHECKONERC721RECEIVED206(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING internal returns (bool) { if (!to.ISCONTRACT794()) { return true; } bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED640(_MSGSENDER48(), from, tokenId, _data); return (retval == _erc721_received341); } function _CLEARAPPROVAL340(uint256 tokenId) private { //inject NONSTANDARD NAMING if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract IERC721Metadata is IERC721 { function NAME105() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL26() external view returns (string memory); //inject NONSTANDARD NAMING function TOKENURI642(uint256 tokenId) external view returns (string memory); //inject NONSTANDARD NAMING } contract MultiTransfer is IERC721 { function TRANSFERBATCH764( //inject NONSTANDARD NAMING address from, address to, uint256 start, uint256 end ) public { for (uint i = start; i < end; i++) { TRANSFERFROM301(from, to, i); } } function TRANSFERALLFROM512( //inject NONSTANDARD NAMING address from, address to, uint256[] memory tokenIDs ) public { for (uint i = 0; i < tokenIDs.length; i++) { TRANSFERFROM301(from, to, tokenIDs[i]); } } function SAFETRANSFERBATCH319( //inject NONSTANDARD NAMING address from, address to, uint256 start, uint256 end ) public { for (uint i = start; i < end; i++) { SAFETRANSFERFROM19(from, to, i); } } function SAFETRANSFERALLFROM526( //inject NONSTANDARD NAMING address from, address to, uint256[] memory tokenIDs ) public { for (uint i = 0; i < tokenIDs.length; i++) { SAFETRANSFERFROM19(from, to, tokenIDs[i]); } } } contract ICards is IERC721 { struct Batch { uint48 userID; uint16 size; } function BATCHES528(uint index) public view returns (uint48 userID, uint16 size); //inject NONSTANDARD NAMING function USERIDTOADDRESS44(uint48 id) public view returns (address); //inject NONSTANDARD NAMING function GETDETAILS612( //inject NONSTANDARD NAMING uint tokenId ) public view returns ( uint16 proto, uint8 quality ); function SETQUALITY366( //inject NONSTANDARD NAMING uint tokenId, uint8 quality ) public; function MINTCARDS596( //inject NONSTANDARD NAMING address to, uint16[] memory _protos, uint8[] memory _qualities ) public returns (uint); function MINTCARD737( //inject NONSTANDARD NAMING address to, uint16 _proto, uint8 _quality ) public returns (uint); function BURN6(uint tokenId) public; //inject NONSTANDARD NAMING function BATCHSIZE292() //inject NONSTANDARD NAMING public view returns (uint); } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant _interface_id_erc721_metadata499 = 0x5b5e139f; //inject NONSTANDARD NAMING constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE770(_interface_id_erc721_metadata499); } function NAME105() external view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL26() external view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING require(_EXISTS289(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } function _SETTOKENURI974(uint256 tokenId, string memory uri) internal { //inject NONSTANDARD NAMING require(_EXISTS289(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } function _BURN121(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._BURN121(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract BatchToken is ERC721Metadata { using SafeMath for uint256; struct Batch { uint48 userID; uint16 size; } mapping(uint48 => address) public userIDToAddress; mapping(address => uint48) public addressToUserID; uint256 public batchSize; uint256 public nextBatch; uint256 public tokenCount; uint48[] internal ownerIDs; uint48[] internal approvedIDs; mapping(uint => Batch) public batches; uint48 internal userCount = 1; mapping(address => uint) internal _balances; uint256 internal constant max_length549 = uint(2**256 - 1); //inject NONSTANDARD NAMING constructor( uint256 _batchSize, string memory name, string memory symbol ) public ERC721Metadata(name, symbol) { batchSize = _batchSize; ownerIDs.length = max_length549; approvedIDs.length = max_length549; } function _GETUSERID7(address to) //inject NONSTANDARD NAMING internal returns (uint48) { if (to == address(0)) { return 0; } uint48 uID = addressToUserID[to]; if (uID == 0) { require( userCount + 1 > userCount, "BT: must not overflow" ); uID = userCount++; userIDToAddress[uID] = to; addressToUserID[to] = uID; } return uID; } function _BATCHMINT199( //inject NONSTANDARD NAMING address to, uint16 size ) internal returns (uint) { require( to != address(0), "BT: must not be null" ); require( size > 0 && size <= batchSize, "BT: size must be within limits" ); uint256 start = nextBatch; uint48 uID = _GETUSERID7(to); batches[start] = Batch({ userID: uID, size: size }); uint256 end = start.ADD640(size); for (uint256 i = start; i < end; i++) { emit TRANSFER336(address(0), to, i); } nextBatch = nextBatch.ADD640(batchSize); _balances[to] = _balances[to].ADD640(size); tokenCount = tokenCount.ADD640(size); return start; } function GETBATCHSTART864(uint256 tokenId) public view returns (uint) { //inject NONSTANDARD NAMING return tokenId.DIV27(batchSize).MUL119(batchSize); } function GETBATCH853(uint256 index) public view returns (uint48 userID, uint16 size) { //inject NONSTANDARD NAMING return (batches[index].userID, batches[index].size); } // Overridden ERC721 functions // @OZ: please stop making variables/functions private function OWNEROF127(uint256 tokenId) //inject NONSTANDARD NAMING public view returns (address) { uint48 uID = ownerIDs[tokenId]; if (uID == 0) { uint256 start = GETBATCHSTART864(tokenId); Batch memory b = batches[start]; require( start + b.size > tokenId, "BT: token does not exist" ); uID = b.userID; require( uID != 0, "BT: bad batch owner" ); } return userIDToAddress[uID]; } function _TRANSFERFROM539( //inject NONSTANDARD NAMING address from, address to, uint256 tokenId ) internal { require( OWNEROF127(tokenId) == from, "BT: transfer of token that is not own" ); require( to != address(0), "BT: transfer to the zero address" ); require( _ISAPPROVEDOROWNER149(msg.sender, tokenId), "BT: caller is not owner nor approved" ); _CANCELAPPROVAL409(tokenId); _balances[from] = _balances[from].SUB596(1); _balances[to] = _balances[to].ADD640(1); ownerIDs[tokenId] = _GETUSERID7(to); emit TRANSFER336(from, to, tokenId); } function _BURN121(uint256 tokenId) internal { //inject NONSTANDARD NAMING require( _ISAPPROVEDOROWNER149(msg.sender, tokenId), "BT: caller is not owner nor approved" ); _CANCELAPPROVAL409(tokenId); address owner = OWNEROF127(tokenId); _balances[owner] = _balances[owner].SUB596(1); ownerIDs[tokenId] = 0; tokenCount = tokenCount.SUB596(1); emit TRANSFER336(owner, address(0), tokenId); } function _CANCELAPPROVAL409(uint256 tokenId) internal { //inject NONSTANDARD NAMING if (approvedIDs[tokenId] != 0) { approvedIDs[tokenId] = 0; } } function APPROVE921(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING address owner = OWNEROF127(tokenId); require( to != owner, "BT: approval to current owner" ); require( msg.sender == owner || ISAPPROVEDFORALL999(owner, msg.sender), "BT: approve caller is not owner nor approved for all" ); approvedIDs[tokenId] = _GETUSERID7(to); emit APPROVAL97(owner, to, tokenId); } function _EXISTS289(uint256 tokenId) //inject NONSTANDARD NAMING internal view returns (bool) { return OWNEROF127(tokenId) != address(0); } function GETAPPROVED252(uint256 tokenId) //inject NONSTANDARD NAMING public view returns (address) { require( _EXISTS289(tokenId), "BT: approved query for nonexistent token" ); return userIDToAddress[approvedIDs[tokenId]]; } function TOTALSUPPLY762() //inject NONSTANDARD NAMING public view returns (uint) { return tokenCount; } function BALANCEOF188(address _owner) //inject NONSTANDARD NAMING public view returns (uint256) { return _balances[_owner]; } } // solium-disable security/no-inline-assembly contract NewCards is Ownable, MultiTransfer, BatchToken, InscribableToken { uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING uint16[] internal cardProtos; uint8[] internal cardQualities; struct Season { uint16 high; uint16 low; } struct Proto { bool locked; bool exists; uint8 god; uint8 cardType; uint8 rarity; uint8 mana; uint8 attack; uint8 health; uint8 tribe; } event PROTOUPDATED864( //inject NONSTANDARD NAMING uint16 indexed id ); event SEASONSTARTED899( //inject NONSTANDARD NAMING uint16 indexed id, string name, uint16 indexed low, uint16 indexed high ); event QUALITYCHANGED816( //inject NONSTANDARD NAMING uint256 indexed tokenId, uint8 quality, address factory ); event CARDSMINTED263( //inject NONSTANDARD NAMING uint256 indexed start, address to, uint16[] protos, uint8[] qualities ); // Value of index proto = season uint16[] public protoToSeason; address public propertyManager; // Array containing all protos Proto[] public protos; // Array containing all seasons Season[] public seasons; // Map whether a season is tradeable or not mapping(uint256 => bool) public seasonTradable; // Map whether a factory has been authorised or not mapping(address => mapping(uint256 => bool)) public factoryApproved; // Whether a factory is approved to create a particular mythic mapping(uint16 => mapping(address => bool)) public mythicApproved; // Whether a mythic is tradable mapping(uint16 => bool) public mythicTradable; // Map whether a mythic exists or not mapping(uint16 => bool) public mythicCreated; uint16 public constant mythic_threshold683 = 65000; //inject NONSTANDARD NAMING constructor( uint256 _batchSize, string memory _name, string memory _symbol ) public BatchToken(_batchSize, _name, _symbol) { cardProtos.length = max_length549; cardQualities.length = max_length549; protoToSeason.length = max_length549; protos.length = max_length549; propertyManager = msg.sender; } function GETDETAILS612( //inject NONSTANDARD NAMING uint256 tokenId ) public view returns (uint16 proto, uint8 quality) { return (cardProtos[tokenId], cardQualities[tokenId]); } function MINTCARD737( //inject NONSTANDARD NAMING address to, uint16 _proto, uint8 _quality ) public returns (uint id) { id = _BATCHMINT199(to, 1); _VALIDATEPROTO247(_proto); cardProtos[id] = _proto; cardQualities[id] = _quality; uint16[] memory ps = new uint16[](1); ps[0] = _proto; uint8[] memory qs = new uint8[](1); qs[0] = _quality; emit CARDSMINTED263(id, to, ps, qs); return id; } function MINTCARDS596( //inject NONSTANDARD NAMING address to, uint16[] memory _protos, uint8[] memory _qualities ) public returns (uint) { require( _protos.length > 0, "Core: must be some protos" ); require( _protos.length == _qualities.length, "Core: must be the same number of protos/qualities" ); uint256 start = _BATCHMINT199(to, uint16(_protos.length)); _VALIDATEANDSAVEDETAILS366(start, _protos, _qualities); emit CARDSMINTED263(start, to, _protos, _qualities); return start; } function ADDFACTORY224( //inject NONSTANDARD NAMING address _factory, uint256 _season ) public ONLYOWNER453 { require( seasons.length >= _season, "Core: season must exist" ); require( _season > 0, "Core: season must not be 0" ); require( !factoryApproved[_factory][_season], "Core: this factory is already approved" ); require( !seasonTradable[_season], "Core: season must not be tradable" ); factoryApproved[_factory][_season] = true; } function APPROVEFORMYTHIC801( //inject NONSTANDARD NAMING address _factory, uint16 _mythic ) public ONLYOWNER453 { require( _mythic >= mythic_threshold683, "not a mythic" ); require( !mythicApproved[_mythic][_factory], "Core: this factory is already approved for this mythic" ); mythicApproved[_mythic][_factory] = true; } function MAKEMYTHICTRADABLE762( //inject NONSTANDARD NAMING uint16 _mythic ) public ONLYOWNER453 { require( _mythic >= mythic_threshold683, "Core: not a mythic" ); require( !mythicTradable[_mythic], "Core: must not be tradable already" ); mythicTradable[_mythic] = true; } function UNLOCKTRADING32( //inject NONSTANDARD NAMING uint256 _season ) public ONLYOWNER453 { require( _season > 0 && _season <= seasons.length, "Core: must be a current season" ); require( !seasonTradable[_season], "Core: season must not be tradable" ); seasonTradable[_season] = true; } function _TRANSFERFROM539( //inject NONSTANDARD NAMING address from, address to, uint256 tokenId ) internal { require( ISTRADABLE528(tokenId), "Core: not yet tradable" ); super._TRANSFERFROM539(from, to, tokenId); } function BURN6(uint256 _tokenId) public { //inject NONSTANDARD NAMING require( ISTRADABLE528(_tokenId), "Core: not yet tradable" ); super._BURN121(_tokenId); } function BURNALL763(uint256[] memory tokenIDs) public { //inject NONSTANDARD NAMING for (uint256 i = 0; i < tokenIDs.length; i++) { BURN6(tokenIDs[i]); } } function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING uint16 proto = cardProtos[_tokenId]; if (proto >= mythic_threshold683) { return mythicTradable[proto]; } return seasonTradable[protoToSeason[proto]]; } function STARTSEASON259( //inject NONSTANDARD NAMING string memory name, uint16 low, uint16 high ) public ONLYOWNER453 returns (uint) { require( low > 0, "Core: must not be zero proto" ); require( high > low, "Core: must be a valid range" ); require( seasons.length == 0 || low > seasons[seasons.length - 1].high, "Core: seasons cannot overlap" ); require( mythic_threshold683 > high, "Core: cannot go into mythic territory" ); // seasons start at 1 uint16 id = uint16(seasons.push(Season({ high: high, low: low }))); uint256 cp; assembly { cp := protoToSeason_slot } StorageWrite.REPEATUINT16794(cp, low, (high - low) + 1, id); emit SEASONSTARTED899(id, name, low, high); return id; } function UPDATEPROTOS359( //inject NONSTANDARD NAMING uint16[] memory _ids, uint8[] memory _gods, uint8[] memory _cardTypes, uint8[] memory _rarities, uint8[] memory _manas, uint8[] memory _attacks, uint8[] memory _healths, uint8[] memory _tribes ) public ONLYOWNER453 { for (uint256 i = 0; i < _ids.length; i++) { uint16 id = _ids[i]; require( id > 0, "Core: proto must not be zero" ); Proto memory proto = protos[id]; require( !proto.locked, "Core: proto is locked" ); protos[id] = Proto({ locked: false, exists: true, god: _gods[i], cardType: _cardTypes[i], rarity: _rarities[i], mana: _manas[i], attack: _attacks[i], health: _healths[i], tribe: _tribes[i] }); emit PROTOUPDATED864(id); } } function LOCKPROTOS122(uint16[] memory _ids) public ONLYOWNER453 { //inject NONSTANDARD NAMING require( _ids.length > 0, "must lock some" ); for (uint256 i = 0; i < _ids.length; i++) { uint16 id = _ids[i]; require( id > 0, "proto must not be zero" ); Proto storage proto = protos[id]; require( !proto.locked, "proto is locked" ); require( proto.exists, "proto must exist" ); proto.locked = true; emit PROTOUPDATED864(id); } } function _VALIDATEANDSAVEDETAILS366( //inject NONSTANDARD NAMING uint256 start, uint16[] memory _protos, uint8[] memory _qualities ) internal { _VALIDATEPROTOS731(_protos); uint256 cp; assembly { cp := cardProtos_slot } StorageWrite.UINT16S436(cp, start, _protos); uint256 cq; assembly { cq := cardQualities_slot } StorageWrite.UINT8S318(cq, start, _qualities); } function _VALIDATEPROTO247(uint16 proto) internal { //inject NONSTANDARD NAMING if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { uint256 season = protoToSeason[proto]; require( season != 0, "Core: must have season set" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING uint16 maxProto = 0; uint16 minProto = max_uint16315; for (uint256 i = 0; i < _protos.length; i++) { uint16 proto = _protos[i]; if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { if (proto > maxProto) { maxProto = proto; } if (minProto > proto) { minProto = proto; } } } if (maxProto != 0) { uint256 season = protoToSeason[maxProto]; // cards must be from the same season require( season != 0, "Core: must have season set" ); require( season == protoToSeason[minProto], "Core: can only create cards from the same season" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } function _CHECKCANCREATEMYTHIC255(uint16 proto) internal { //inject NONSTANDARD NAMING require( mythicApproved[proto][msg.sender], "Core: not approved to create this mythic" ); require( !mythicCreated[proto], "Core: mythic has already been created" ); mythicCreated[proto] = true; } function SETQUALITY366( //inject NONSTANDARD NAMING uint256 _tokenId, uint8 _quality ) public { uint16 proto = cardProtos[_tokenId]; // wont' be able to change mythic season uint256 season = protoToSeason[proto]; require( factoryApproved[msg.sender][season], "Core: factory can't change quality of this season" ); cardQualities[_tokenId] = _quality; emit QUALITYCHANGED816(_tokenId, _quality, msg.sender); } function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { //inject NONSTANDARD NAMING propertyManager = _manager; } function SETPROPERTY942(uint256 _id, bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING require( msg.sender == propertyManager, "Core: must be property manager" ); _SETPROPERTY292(_id, _key, _value); } function SETCLASSPROPERTY520(bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING require( msg.sender == propertyManager, "Core: must be property manager" ); _SETCLASSPROPERTY718(_key, _value); } string public baseURI = "https://api.immutable.com/asset/"; function SETBASEURI249(string memory uri) public ONLYOWNER453 { //inject NONSTANDARD NAMING baseURI = uri; } function TOKENURI642(uint256 tokenId) external view returns (string memory) { //inject NONSTANDARD NAMING return string(abi.encodePacked( baseURI, String.FROMADDRESS777(address(this)), "/", String.FROMUINT947(tokenId) )); } } // solium-disable security/no-inline-assembly contract Cards is Ownable, MultiTransfer, BatchToken, ImmutableToken, InscribableToken { uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING uint16[] public cardProtos; uint8[] public cardQualities; struct Season { uint16 high; uint16 low; } struct Proto { bool locked; bool exists; uint8 god; uint8 cardType; uint8 rarity; uint8 mana; uint8 attack; uint8 health; uint8 tribe; } event PROTOUPDATED864( //inject NONSTANDARD NAMING uint16 indexed id ); event SEASONSTARTED899( //inject NONSTANDARD NAMING uint16 indexed id, string name, uint16 indexed low, uint16 indexed high ); event QUALITYCHANGED816( //inject NONSTANDARD NAMING uint256 indexed tokenId, uint8 quality, address factory ); event CARDSMINTED263( //inject NONSTANDARD NAMING uint256 indexed start, address to, uint16[] protos, uint8[] qualities ); // Value of index proto = season uint16[] public protoToSeason; address public propertyManager; // Array containing all protos Proto[] public protos; // Array containing all seasons Season[] public seasons; // Map whether a season is tradeable or not mapping(uint256 => bool) public seasonTradable; // Map whether a factory has been authorised or not mapping(address => mapping(uint256 => bool)) public factoryApproved; // Whether a factory is approved to create a particular mythic mapping(uint16 => mapping(address => bool)) public mythicApproved; // Whether a mythic is tradable mapping(uint16 => bool) public mythicTradable; // Map whether a mythic exists or not mapping(uint16 => bool) public mythicCreated; uint16 public constant mythic_threshold683 = 65000; //inject NONSTANDARD NAMING constructor( uint256 _batchSize, string memory _name, string memory _symbol ) public BatchToken(_batchSize, _name, _symbol) { cardProtos.length = max_length549; cardQualities.length = max_length549; protoToSeason.length = max_length549; protos.length = max_length549; propertyManager = msg.sender; } function GETDETAILS612( //inject NONSTANDARD NAMING uint256 tokenId ) public view returns (uint16 proto, uint8 quality) { return (cardProtos[tokenId], cardQualities[tokenId]); } function MINTCARD737( //inject NONSTANDARD NAMING address to, uint16 _proto, uint8 _quality ) external returns (uint id) { id = _BATCHMINT199(to, 1); _VALIDATEPROTO247(_proto); cardProtos[id] = _proto; cardQualities[id] = _quality; uint16[] memory ps = new uint16[](1); ps[0] = _proto; uint8[] memory qs = new uint8[](1); qs[0] = _quality; emit CARDSMINTED263(id, to, ps, qs); return id; } function MINTCARDS596( //inject NONSTANDARD NAMING address to, uint16[] calldata _protos, uint8[] calldata _qualities ) external returns (uint) { require( _protos.length > 0, "Core: must be some protos" ); require( _protos.length == _qualities.length, "Core: must be the same number of protos/qualities" ); uint256 start = _BATCHMINT199(to, uint16(_protos.length)); _VALIDATEANDSAVEDETAILS366(start, _protos, _qualities); emit CARDSMINTED263(start, to, _protos, _qualities); return start; } function ADDFACTORY224( //inject NONSTANDARD NAMING address _factory, uint256 _season ) public ONLYOWNER453 { require( seasons.length >= _season, "Core: season must exist" ); require( _season > 0, "Core: season must not be 0" ); require( !factoryApproved[_factory][_season], "Core: this factory is already approved" ); require( !seasonTradable[_season], "Core: season must not be tradable" ); factoryApproved[_factory][_season] = true; } function APPROVEFORMYTHIC801( //inject NONSTANDARD NAMING address _factory, uint16 _mythic ) public ONLYOWNER453 { require( _mythic >= mythic_threshold683, "not a mythic" ); require( !mythicApproved[_mythic][_factory], "Core: this factory is already approved for this mythic" ); mythicApproved[_mythic][_factory] = true; } function MAKEMYTHICTRADABLE762( //inject NONSTANDARD NAMING uint16 _mythic ) public ONLYOWNER453 { require( _mythic >= mythic_threshold683, "Core: not a mythic" ); require( !mythicTradable[_mythic], "Core: must not be tradable already" ); mythicTradable[_mythic] = true; } function UNLOCKTRADING32( //inject NONSTANDARD NAMING uint256 _season ) public ONLYOWNER453 { require( _season > 0 && _season <= seasons.length, "Core: must be a current season" ); require( !seasonTradable[_season], "Core: season must not be tradable" ); seasonTradable[_season] = true; } function TRANSFERFROM301( //inject NONSTANDARD NAMING address from, address to, uint256 tokenId ) public { require( ISTRADABLE528(tokenId), "Core: not yet tradable" ); super.TRANSFERFROM301(from, to, tokenId); } function BURN6(uint256 _tokenId) public { //inject NONSTANDARD NAMING require( ISTRADABLE528(_tokenId), "Core: not yet tradable" ); super._BURN121(_tokenId); } function BURNALL763(uint256[] memory tokenIDs) public { //inject NONSTANDARD NAMING for (uint256 i = 0; i < tokenIDs.length; i++) { BURN6(tokenIDs[i]); } } function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING uint16 proto = cardProtos[_tokenId]; if (proto >= mythic_threshold683) { return mythicTradable[proto]; } return seasonTradable[protoToSeason[proto]]; } function STARTSEASON259( //inject NONSTANDARD NAMING string memory name, uint16 low, uint16 high ) public ONLYOWNER453 returns (uint) { require( low > 0, "Core: must not be zero proto" ); require( high > low, "Core: must be a valid range" ); require( seasons.length == 0 || low > seasons[seasons.length - 1].high, "Core: seasons cannot overlap" ); require( mythic_threshold683 > high, "Core: cannot go into mythic territory" ); // seasons start at 1 uint16 id = uint16(seasons.push(Season({ high: high, low: low }))); uint256 cp; assembly { cp := protoToSeason_slot } StorageWrite.REPEATUINT16794(cp, low, (high - low) + 1, id); emit SEASONSTARTED899(id, name, low, high); return id; } function UPDATEPROTOS359( //inject NONSTANDARD NAMING uint16[] memory _ids, uint8[] memory _gods, uint8[] memory _cardTypes, uint8[] memory _rarities, uint8[] memory _manas, uint8[] memory _attacks, uint8[] memory _healths, uint8[] memory _tribes ) public ONLYOWNER453 { for (uint256 i = 0; i < _ids.length; i++) { uint16 id = _ids[i]; require( id > 0, "Core: proto must not be zero" ); Proto memory proto = protos[id]; require( !proto.locked, "Core: proto is locked" ); protos[id] = Proto({ locked: false, exists: true, god: _gods[i], cardType: _cardTypes[i], rarity: _rarities[i], mana: _manas[i], attack: _attacks[i], health: _healths[i], tribe: _tribes[i] }); emit PROTOUPDATED864(id); } } function LOCKPROTOS122(uint16[] memory _ids) public ONLYOWNER453 { //inject NONSTANDARD NAMING require( _ids.length > 0, "must lock some" ); for (uint256 i = 0; i < _ids.length; i++) { uint16 id = _ids[i]; require( id > 0, "proto must not be zero" ); Proto storage proto = protos[id]; require( !proto.locked, "proto is locked" ); require( proto.exists, "proto must exist" ); proto.locked = true; emit PROTOUPDATED864(id); } } function _VALIDATEANDSAVEDETAILS366( //inject NONSTANDARD NAMING uint256 start, uint16[] memory _protos, uint8[] memory _qualities ) internal { _VALIDATEPROTOS731(_protos); uint256 cp; assembly { cp := cardProtos_slot } StorageWrite.UINT16S436(cp, start, _protos); uint256 cq; assembly { cq := cardQualities_slot } StorageWrite.UINT8S318(cq, start, _qualities); } function _VALIDATEPROTO247(uint16 proto) internal { //inject NONSTANDARD NAMING if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { uint256 season = protoToSeason[proto]; require( season != 0, "Core: must have season set" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING uint16 maxProto = 0; uint16 minProto = max_uint16315; for (uint256 i = 0; i < _protos.length; i++) { uint16 proto = _protos[i]; if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { if (proto > maxProto) { maxProto = proto; } if (minProto > proto) { minProto = proto; } } } if (maxProto != 0) { uint256 season = protoToSeason[maxProto]; // cards must be from the same season require( season != 0, "Core: must have season set" ); require( season == protoToSeason[minProto], "Core: can only create cards from the same season" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } function _CHECKCANCREATEMYTHIC255(uint16 proto) internal { //inject NONSTANDARD NAMING require( mythicApproved[proto][msg.sender], "Core: not approved to create this mythic" ); require( !mythicCreated[proto], "Core: mythic has already been created" ); mythicCreated[proto] = true; } function SETQUALITY366( //inject NONSTANDARD NAMING uint256 _tokenId, uint8 _quality ) public { uint16 proto = cardProtos[_tokenId]; // wont' be able to change mythic season uint256 season = protoToSeason[proto]; require( factoryApproved[msg.sender][season], "Core: factory can't change quality of this season" ); cardQualities[_tokenId] = _quality; emit QUALITYCHANGED816(_tokenId, _quality, msg.sender); } function SETPROPERTYMANAGER70(address _manager) public ONLYOWNER453 { //inject NONSTANDARD NAMING propertyManager = _manager; } function SETPROPERTY942(uint256 _id, bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING require( msg.sender == propertyManager, "Core: must be property manager" ); _SETPROPERTY292(_id, _key, _value); } function SETCLASSPROPERTY520(bytes32 _key, bytes32 _value) public { //inject NONSTANDARD NAMING require( msg.sender == propertyManager, "Core: must be property manager" ); _SETCLASSPROPERTY718(_key, _value); } } contract BatchWrapper is NewCards { uint16 private constant max_uint16315 = 2**16 - 1; //inject NONSTANDARD NAMING Cards public old; bool public migrating; constructor( Cards _old, uint256 _batchSize, string memory _name, string memory _symbol ) public NewCards(_batchSize, _name, _symbol) { old = _old; } function SETMIGRATING202(bool _migrating) public ONLYOWNER453 { //inject NONSTANDARD NAMING migrating = _migrating; } function COPYUNTIL891(uint gasThreshold) public { //inject NONSTANDARD NAMING while (gasleft() > gasThreshold) { COPYNEXTBATCH144(); } } function MINTCARDS596(address _to, uint16[] memory _protos, uint8[] memory _qualities) public returns (uint id) { //inject NONSTANDARD NAMING require(!migrating, "must not be migrating"); super.MINTCARDS596(_to, _protos, _qualities); } function MINTCARD737(address _to, uint16 _proto, uint8 _quality) public returns (uint id) { //inject NONSTANDARD NAMING require(!migrating, "must not be migrating"); super.MINTCARD737(_to, _proto, _quality); } // copy all batches from the old contracts // leave ids intact function COPYNEXTBATCH144() public { //inject NONSTANDARD NAMING require(migrating, "must be migrating"); uint256 start = nextBatch; (uint48 userID, uint16 size) = old.batches(start); require(size > 0 && userID > 0, "incorrect batch or limit reached"); if (old.cardProtos(start) != 0) { address to = old.userIDToAddress(userID); uint48 uID = _GETUSERID7(to); batches[start] = Batch({ userID: uID, size: size }); uint256 end = start.ADD640(size); for (uint256 i = start; i < end; i++) { emit TRANSFER336(address(0), to, i); } _balances[to] = _balances[to].ADD640(size); tokenCount = tokenCount.ADD640(size); } nextBatch = nextBatch.ADD640(batchSize); } function ISOLD374(uint _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING require(_EXISTS289(_tokenId), "card does not exist"); return cardProtos[_tokenId] == 0; } function GETPROTO912(uint _tokenId) public view returns (uint16) { //inject NONSTANDARD NAMING return ISOLD374(_tokenId) ? old.cardProtos(_tokenId) : cardProtos[_tokenId]; } function GETQUALITY41(uint _tokenId) public view returns (uint8) { //inject NONSTANDARD NAMING return ISOLD374(_tokenId) ? old.cardQualities(_tokenId) : cardQualities[_tokenId]; } function GETDETAILS612(uint256 tokenId) public view returns (uint16 proto, uint8 quality) { //inject NONSTANDARD NAMING return ISOLD374(tokenId) ? old.GETDETAILS612(tokenId) : (cardProtos[tokenId], cardQualities[tokenId]); } function ISTRADABLE528(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING uint16 proto = GETPROTO912(_tokenId); if (proto >= mythic_threshold683) { return mythicTradable[proto]; } return seasonTradable[protoToSeason[proto]]; } function _TRANSFERFROM539(address from, address to, uint tokenId) internal { //inject NONSTANDARD NAMING require( ISTRADABLE528(tokenId), "BW: not yet tradable" ); super._TRANSFERFROM539(from, to, tokenId); } // update validate protos to check if a proto is 0 // prevent untradable cards function _VALIDATEPROTOS731(uint16[] memory _protos) internal { //inject NONSTANDARD NAMING uint16 maxProto = 0; uint16 minProto = max_uint16315; for (uint256 i = 0; i < _protos.length; i++) { uint16 proto = _protos[i]; if (proto >= mythic_threshold683) { _CHECKCANCREATEMYTHIC255(proto); } else { require(proto != 0, "proto is zero"); if (proto > maxProto) { maxProto = proto; } if (minProto > proto) { minProto = proto; } } } if (maxProto != 0) { uint256 season = protoToSeason[maxProto]; // cards must be from the same season require( season != 0, "Core: must have season set" ); require( season == protoToSeason[minProto], "Core: can only create cards from the same season" ); require( factoryApproved[msg.sender][season], "Core: must be approved factory for this season" ); } } }
inject NONSTANDARD NAMING
function MINTCARD737(address _to, uint16 _proto, uint8 _quality) public returns (uint id) {
2,483,656
./partial_match/1/0xAd100C81305244a32372Bc307AB247864ce6c68a/sources/BKRW.sol
return Numerator of addr's transferFee./
function individualTransferFeeNumerator(address addr) public view returns (uint256) { return _individualTransferFee[addr].numerator; }
3,982,373
./full_match/4/0xf731D2B13D4B4bD66518df6CCd369E34Dc1F737a/sources/contracts/ABC.sol
Change the address of the treasury wallet _treasuryWallet The new address of the treasury wallet
function setTreasuryWallet(address payable _treasuryWallet) external onlyOwner() { treasuryWallet = _treasuryWallet; }
780,926
/* ▄▄▄█████▓ ██░ ██ ▓█████ ██▀███ ██▓ █████▒▄▄▄█████▓ (for Adventurers) ▓ ██▒ ▓▒▓██░ ██▒▓█ ▀ ▓██ ▒ ██▒▓██▒▓██ ▒ ▓ ██▒ ▓▒ ▒ ▓██░ ▒░▒██▀▀██░▒███ ▓██ ░▄█ ▒▒██▒▒████ ░ ▒ ▓██░ ▒░ ░ ▓██▓ ░ ░▓█ ░██ ▒▓█ ▄ ▒██▀▀█▄ ░██░░▓█▒ ░ ░ ▓██▓ ░ ▒██▒ ░ ░▓█▒░██▓░▒████▒ ░██▓ ▒██▒░██░░▒█░ ▒██▒ ░ ▒ ░░ ▒ ░░▒░▒░░ ▒░ ░ ░ ▒▓ ░▒▓░░▓ ▒ ░ ▒ ░░ ░ ▒ ░▒░ ░ ░ ░ ░ ░▒ ░ ▒░ ▒ ░ ░ ░ ░ ░ ░░ ░ ░ ░░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ by chris and tony */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "./Interfaces.sol"; import "./IRift.sol"; /* You've heard it calling... Now it's time to level up your Adventure! Enter The Rift, and gain its power. Take too much, and all suffer. Return what you've gained, and all benefit.. -------------------------------------------- The Rift creates a bridge between Loot derivatives and the bags that play and interact with them. Bags that interact with derivatives are rewarded with XP, Levels, and Rift Charges. Any derivative can read a bag's XP & Level from the Rift. This enables support for things like: - Dynamic items that scale with bag levels - Level-based Dungeon difficulties - Experienced-based Lore more @ https://rift.live */ contract Rift is Initializable, ReentrancyGuardUpgradeable, PausableUpgradeable, OwnableUpgradeable { event AddCharge(address indexed owner, uint256 indexed tokenId, uint16 amount, uint16 forLvl); event AwardXP(uint256 indexed tokenId, uint256 amount); event UseCharge(address indexed owner, address indexed riftObject, uint256 indexed tokenId, uint16 amount); event ObjectSacrificed(address indexed owner, address indexed object, uint256 tokenId, uint256 indexed bagId, uint256 powerIncrease); // The Rift supports 8000 Loot bags // 9989460 mLoot Bags (34 years worth) // and 2540 gLoot Bags IERC721 public iLoot; IERC721 public iMLoot; IERC721 public iGLoot; IMana public iMana; IRiftData public iRiftData; // gLoot bags must offset their bagId by adding gLootOffset when interacting uint32 constant glootOffset = 9997460; string public description; /* Rift power will decrease as bags level up and gain charges. Charges will create Rift Objects. Rift Objects can be burned into the Rift to amplify its power. If Rift Level reaches 0, no more charges are created. */ uint32 public riftLevel; uint256 public riftPower; uint8 internal riftLevelIncreasePercentage; uint8 internal riftLevelDecreasePercentage; uint256 internal riftLevelMinThreshold; uint256 internal riftLevelMaxThreshold; uint256 internal riftCallibratedTime; uint64 public riftObjectsSacrificed; mapping(uint16 => uint16) public levelChargeAward; mapping(address => bool) public riftObjects; mapping(address => bool) public riftQuests; mapping(address => BurnableObject) public staticBurnObjects; address[] public riftObjectsArr; address[] public staticBurnableArr; mapping(uint256 => ChargeData) public chargesData; uint256 public chargeMod; // bag creates charge every `chargeMod` levels uint256 public chargeRate; // bag creates a charge every `chargeRate` days function initialize() public initializer { __Ownable_init(); __Pausable_init(); __ReentrancyGuard_init(); } function ownerSetDescription(string memory desc) external onlyOwner { description = desc; } function ownerSetManaAddress(address addr) external onlyOwner { iMana = IMana(addr); } function ownerSetRiftData(address addr) external onlyOwner { iRiftData = IRiftData(addr); } function addRiftQuest(address addr) external onlyOwner { riftQuests[addr] = true; } function removeRiftQuest(address addr) external onlyOwner { riftQuests[addr] = false; } /** * enables an address to mint / burn * @param controller the address to enable */ function addRiftObject(address controller) external onlyOwner { riftObjects[controller] = true; riftObjectsArr.push(controller); } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeRiftObject(address controller) external onlyOwner { riftObjects[controller] = false; } function addStaticBurnable(address burnable, uint64 _power, uint32 _mana, uint16 _xp) external onlyOwner { staticBurnObjects[burnable] = BurnableObject({ power: _power, mana: _mana, xp: _xp }); staticBurnableArr.push(burnable); } function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function ownerWithdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function ownerSetLevelChargeAward(uint16 level, uint16 charges) external onlyOwner { levelChargeAward[level] = charges; } function ownerSetChargeGen(uint256 _mod, uint256 _rate) external onlyOwner { chargeMod = _mod; chargeRate = _rate; } // READ function isBagHolder(uint256 bagId, address owner) _isBagHolder(bagId, owner) external view {} function getBagInfo(uint256 bagId) external view returns (RiftBagInfo memory) { return RiftBagInfo({ charges: uint64(getCharges(bagId)), chargesUsed: chargesData[bagId].chargesUsed, chargesPurchased: chargesData[bagId].chargesPurchased, lastChargePurchased: chargesData[bagId].lastPurchase, xp: iRiftData.xpMap(bagId), level: iRiftData.getLevel(bagId) }); } // WRITE /** * DEPRECATED * @dev purchase a Rift Charge with Mana * @param bagId bag that will be given the charge */ // function buyCharge(uint256 bagId) external // _isBagHolder(bagId, _msgSender()) // whenNotPaused // nonReentrant { // ChargeData memory cd = chargesData[bagId]; // require(block.timestamp - cd.lastPurchase > 1 days, "Too soon"); // require(riftLevel > 0, "rift has no power"); // iMana.burn(_msgSender(), iRiftData.getLevel(bagId) * ((bagId < 8001 || bagId > glootOffset) ? 100 : 10)); // chargesData[bagId] = ChargeData({ // chargesPurchased: cd.chargesPurchased + 1, // chargesUsed: cd.chargesUsed, // lastPurchase: uint128(block.timestamp) // }); // } function useCharge(uint16 amount, uint256 bagId, address from) _isBagHolder(bagId, from) external whenNotPaused nonReentrant { require(riftObjects[msg.sender], "Not of the Rift"); require(getCharges(bagId) >= amount, "Not enough charges"); ChargeData memory cd = chargesData[bagId]; chargesData[bagId] = ChargeData({ chargesPurchased: cd.chargesPurchased, chargesUsed: (block.timestamp - cd.lastPurchase < (chargeRate * 1 days)) ? cd.chargesUsed += amount : cd.chargesUsed += amount - 1, lastPurchase: (block.timestamp - cd.lastPurchase < (chargeRate * 1 days)) ? cd.lastPurchase : uint128(block.timestamp) }); emit UseCharge(from, _msgSender(), bagId, amount); } // give 1 charge for first level // give 1 charge every chargeMod levels // gain 1 charge after chargeRate days (does not stack) function getCharges(uint256 bagId) public view returns (uint256) { uint256 lvl = iRiftData.getLevel(bagId); uint256 charges = 1; // 1 charge every chargeMod levels charges += (lvl / chargeMod); // make sure charges aren't negative if (chargesData[bagId].chargesUsed > (charges + chargesData[bagId].chargesPurchased)) { charges = 0; } else { // purchased charges are deprecated, but still honored for anyone that purchased before deprecation charges = charges + chargesData[bagId].chargesPurchased - chargesData[bagId].chargesUsed; } // extra charge if (block.timestamp - chargesData[bagId].lastPurchase >= (chargeRate * 1 days)) { charges += 1; } return charges; } /** * @dev increases the rift's power by burning an object into it. rewards XP. the burnt object must implement IRiftBurnable * @param burnableAddr address of the object that is getting burned * @param tokenId id of object getting burned * @param bagId id of bag that will get XP */ function growTheRift(address burnableAddr, uint256 tokenId, uint256 bagId) _isBagHolder(bagId, _msgSender()) external whenNotPaused { require(riftObjects[burnableAddr], "Not of the Rift"); require(IERC721(burnableAddr).ownerOf(tokenId) == _msgSender(), "Must be yours"); ERC721BurnableUpgradeable(burnableAddr).burn(tokenId); _rewardBurn(burnableAddr, tokenId, bagId, IRiftBurnable(burnableAddr).burnObject(tokenId)); } /** * @dev increases the rift's power by burning an object into it. rewards XP. * @param burnableAddr address of the object that is getting burned * @param tokenId id of object getting burned * @param bagId id of bag that will get XP */ function growTheRiftStatic(address burnableAddr, uint256 tokenId, uint256 bagId) _isBagHolder(bagId, _msgSender()) external whenNotPaused { require(IERC721(burnableAddr).ownerOf(tokenId) == _msgSender(), "Must be yours"); IERC721(burnableAddr).transferFrom(_msgSender(), 0x000000000000000000000000000000000000dEaD, tokenId); _rewardBurn(burnableAddr, tokenId, bagId, staticBurnObjects[burnableAddr]); } function growTheRiftRewards(address burnableAddr, uint256 tokenId) external view returns (BurnableObject memory) { return IRiftBurnable(burnableAddr).burnObject(tokenId); } function _rewardBurn(address burnableAddr, uint256 tokenId, uint256 bagId, BurnableObject memory bo) internal { riftPower += bo.power; riftObjectsSacrificed += 1; iRiftData.addXP(bo.xp, bagId); iMana.ccMintTo(_msgSender(), bo.mana); emit ObjectSacrificed(_msgSender(), burnableAddr, tokenId, bagId, bo.power); } function addPower(uint256 power) external whenNotPaused { require(riftObjects[msg.sender] == true, "Can't add power"); riftPower += power; } // Rift Power /** * @dev rewards mana for recalibrating the Rift */ function recalibrateRift() external whenNotPaused { require(block.timestamp - riftCallibratedTime >= 1 hours, "wait"); if (riftPower >= riftLevelMaxThreshold) { // up a level riftLevel += 1; uint256 riftLevelPower = riftLevelMaxThreshold - riftLevelMinThreshold; riftLevelMinThreshold = riftLevelMaxThreshold; riftLevelMaxThreshold += riftLevelPower + (riftLevelPower * riftLevelIncreasePercentage)/100; } else if (riftPower < riftLevelMinThreshold) { // down a level if (riftLevel == 1) { riftLevel = 0; riftLevelMinThreshold = 0; riftLevelMaxThreshold = 10000; } else { riftLevel -= 1; uint256 riftLevelPower = riftLevelMaxThreshold - riftLevelMinThreshold; riftLevelMaxThreshold = riftLevelMinThreshold; riftLevelMinThreshold -= riftLevelPower + (riftLevelPower * riftLevelDecreasePercentage)/100; } } iMana.ccMintTo(msg.sender, (block.timestamp - riftCallibratedTime) / (3600) * 10 * riftLevel); riftCallibratedTime = block.timestamp; } // MODIFIERS modifier _isBagHolder(uint256 bagId, address owner) { if (bagId < 8001) { require(iLoot.ownerOf(bagId) == owner, "UNAUTH"); } else if (bagId > glootOffset) { require(iGLoot.ownerOf(bagId - glootOffset) == owner, "UNAUTH"); } else { require(iMLoot.ownerOf(bagId) == owner, "UNAUTH"); } _; } } /* ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌ ▐░░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌ ▐░█▀▀▀▀█░█▀▀ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀ by chris and tony */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; struct RiftBag { uint16 charges; uint32 chargesUsed; uint16 level; uint64 xp; uint64 lastChargePurchase; } interface IRiftData { function updateXP(uint256 xp, uint256 bagId) external; function addKarma(uint64 k, address holder) external; function removeKarma(uint64 k, address holder) external; function karma(address holder) external view returns (uint64); function karmaTotal() external view returns (uint256); function karmaHolders() external view returns (uint256); function addXP(uint256 xp, uint256 bagId) external; function getLevel(uint256 bagId) external view returns (uint256); function xpMap(uint256 bagId) external view returns (uint256); } /* Logic free storage of Rift Data. The intent of this storage is twofold: 1. The data manipulation performed by the Rift is novel (especially to the authors), and this store acts as a failsafe in case a new Rift contract needs to be deployed. 2. The authors' intent is to grant control of this data to more controllers (a DAO, L2 rollup, etc). */ contract RiftData is IRiftData, OwnableUpgradeable { mapping(address => bool) public riftControllers; uint256 public karmaTotal; uint256 public karmaHolders; mapping(uint256 => RiftBag) internal _bags; mapping(address => uint64) public karma; mapping(address => bool) public xpControllers; mapping(uint256 => uint256) public xpMap; function initialize() public initializer { // __Ownable_init(); } function addRiftController(address addr) external onlyOwner { riftControllers[addr] = true; } function removeRiftController(address addr) external onlyOwner { riftControllers[addr] = false; } function addXPController(address addr) external onlyOwner { xpControllers[addr] = true; } function removeXPController(address addr) external onlyOwner { xpControllers[addr] = false; } modifier onlyRiftController() { require(riftControllers[msg.sender], "NOT RIFTCONTROLLER!"); _; } modifier onlyXPController() { require(xpControllers[msg.sender], "NOT XPCONTROLLER!"); _; } function updateXP(uint256 xp, uint256 bagId) external override onlyRiftController { xpMap[bagId] = xp; } function addXP(uint256 xp, uint256 bagId) external override onlyXPController { xpMap[bagId] += xp; } function addKarma(uint64 k, address holder) external override onlyRiftController { if (karma[holder] == 0) { karmaHolders += 1; } karmaTotal += k; karma[holder] += k; } function removeKarma(uint64 k, address holder) external override onlyRiftController { k > karma[holder] ? karma[holder] = 0 : karma[holder] -= k; } function getLevel(uint256 bagId) external override view returns (uint256) { uint256 _xp = xpMap[bagId]; if (_xp < 65) return 1; else if (_xp < 70) return 2; else { return 1 + (sqrt(625+75*_xp)-25)/50; // roughly 15% increase xp per level } } // migrates xp from old system to new function migrateXP(uint256[] memory bagIds) external onlyOwner { for (uint i=0; i < bagIds.length; i++) { xpMap[bagIds[i]] += _bags[bagIds[i]].xp + (_bags[bagIds[i]].level * 125); } } } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function sqrt(uint256 x) pure returns (uint256 result) { if (x == 0) { return 0; } // Calculate the square root of the perfect square of a power of two that is the closest to x. uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; struct Bag { uint64 totalManaProduced; uint64 mintCount; } struct Crystal { uint16 attunement; uint64 lastClaim; uint16 focus; uint32 focusManaProduced; uint32 regNum; uint16 lvlClaims; } interface ICrystalsMetadata { function tokenURI(uint256 tokenId) external view returns (string memory); } interface ICrystals { function crystalsMap(uint256 tokenID) external view returns (Crystal memory); function bags(uint256 tokenID) external view returns (Bag memory); function getResonance(uint256 tokenId) external view returns (uint32); function getSpin(uint256 tokenId) external view returns (uint32); function claimableMana(uint256 tokenID) external view returns (uint32); function availableClaims(uint256 tokenId) external view returns (uint8); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; function transferFrom(address from, address to, uint256 tokenId) external; } /// [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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./RiftData.sol"; interface IRift { function riftLevel() external view returns (uint32); function useCharge(uint16 amount, uint256 bagId, address from) external; function isBagHolder(uint256 bagId, address owner) external; function addPower(uint256 power) external; } struct BagProgress { uint32 lastCompletedStep; bool completedQuest; } struct BurnableObject { uint64 power; uint32 mana; uint16 xp; } struct ChargeData { uint64 chargesPurchased; uint64 chargesUsed; uint128 lastPurchase; } struct RiftBagInfo { uint64 charges; uint64 chargesUsed; uint64 chargesPurchased; uint128 lastChargePurchased; uint256 xp; uint256 level; } interface IRiftBurnable { function burnObject(uint256 tokenId) external view returns (BurnableObject memory); } interface IMana { function ccMintTo(address recipient, uint256 amount) external; function burn(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal onlyInitializing { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) 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 onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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 making 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 // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; }
disables an address from minting / burning controller the address to disbale/
function removeRiftObject(address controller) external onlyOwner { riftObjects[controller] = false; }
256,597
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; import "./interfaces/ICMCWithdraw.sol"; import "./interfaces/WithdrawHelper.sol"; import "./CMCCore.sol"; import "./AssetTransfer.sol"; import "./lib/LibAsset.sol"; import "./lib/LibChannelCrypto.sol"; import "./lib/LibUtils.sol"; contract CMCWithdraw is CMCCore, AssetTransfer, ICMCWithdraw { using LibChannelCrypto for bytes32; mapping(bytes32 => bool) private isExecuted; modifier validateWithdrawData(WithdrawData calldata wd) { require(wd.channelAddress == address(this), "CMCWithdraw: CHANNEL_MISMATCH"); _; } function getWithdrawalTransactionRecord(WithdrawData calldata wd) external override view onlyViaProxy nonReentrantView returns (bool) { return isExecuted[hashWithdrawData(wd)]; } /// @param wd The withdraw data consisting of /// semantic withdraw information, i.e. assetId, recipient, and amount; /// information to make an optional call in addition to the actual transfer, /// i.e. target address for the call and call payload; /// additional information, i.e. channel address and nonce. /// @param aliceSignature Signature of owner a /// @param bobSignature Signature of owner b function withdraw( WithdrawData calldata wd, bytes calldata aliceSignature, bytes calldata bobSignature ) external override onlyViaProxy nonReentrant validateWithdrawData(wd) { // Generate hash bytes32 wdHash = hashWithdrawData(wd); // Verify Alice's and Bob's signature on the withdraw data verifySignatures(wdHash, aliceSignature, bobSignature); // Replay protection require(!isExecuted[wdHash], "CMCWithdraw: ALREADY_EXECUTED"); isExecuted[wdHash] = true; // Determine actually transferable amount uint256 balance = LibAsset.getOwnBalance(wd.assetId); uint256 amount = LibUtils.min(wd.amount, balance); // Revert if amount is zero && callTo is 0 require(amount > 0 || wd.callTo != address(0), "CMCWithdraw: NO_OP"); // Add to totalWithdrawn registerTransfer(wd.assetId, amount); // Execute the transfer require(LibAsset.transfer(wd.assetId, wd.recipient, amount), "CMCWithdraw: ASSET_TRANSFER_FAILED"); // Do we have to make a call in addition to the actual transfer? if (wd.callTo != address(0)) { WithdrawHelper(wd.callTo).execute(wd, amount); } } // TODO: include commitment type function verifySignatures( bytes32 wdHash, bytes calldata aliceSignature, bytes calldata bobSignature ) internal view { require(wdHash.checkSignature(aliceSignature, alice), "CMCWithdraw: INVALID_ALICE_SIG"); require(wdHash.checkSignature(bobSignature, bob), "CMCWithdraw: INVALID_BOB_SIG"); } function hashWithdrawData(WithdrawData calldata wd) internal pure returns (bytes32) { return keccak256(abi.encode(wd)); } }
TODO: include commitment type
function verifySignatures( bytes32 wdHash, bytes calldata aliceSignature, bytes calldata bobSignature ) internal view { require(wdHash.checkSignature(aliceSignature, alice), "CMCWithdraw: INVALID_ALICE_SIG"); require(wdHash.checkSignature(bobSignature, bob), "CMCWithdraw: INVALID_BOB_SIG"); }
12,759,917
//Address: 0x70c1d6d067465c09f539de678af013aad2934cdd //Contract name: Crowdsale //Balance: 0 Ether //Verification Date: 3/19/2018 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public 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); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract BurnableByOwner is BasicToken, Ownable { event Burn(address indexed burner, uint256 value); function burn(address _address, uint256 _value) public onlyOwner{ require(_value <= balances[_address]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = _address; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } contract Wolf is Ownable, MintableToken, BurnableByOwner { using SafeMath for uint256; string public constant name = "Wolf"; string public constant symbol = "Wolf"; uint32 public constant decimals = 18; address public addressTeam; address public addressCashwolf; address public addressFutureInvest; uint public summTeam = 15000000000 * 1 ether; uint public summCashwolf = 10000000000 * 1 ether; uint public summFutureInvest = 10000000000 * 1 ether; function Wolf() public { addressTeam = 0xb5AB520F01DeE8a42A2bfaEa8075398414774778; addressCashwolf = 0x3366e9946DD375d1966c8E09f889Bc18C5E1579A; addressFutureInvest = 0x7134121392eE0b6DC9382BBd8E392B4054CdCcEf; //Founders and supporters initial Allocations balances[addressTeam] = balances[addressTeam].add(summTeam); balances[addressCashwolf] = balances[addressCashwolf].add(summCashwolf); balances[addressFutureInvest] = balances[addressFutureInvest].add(summFutureInvest); totalSupply = summTeam.add(summCashwolf).add(summFutureInvest); } function getTotalSupply() public constant returns(uint256){ return totalSupply; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where Contributors can make * token Contributions and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. The contract requires a MintableToken that will be * minted as contributions arrive, note that the crowdsale contract * must be owner of the token in order to be able to mint it. */ contract Crowdsale is Ownable { using SafeMath for uint256; // soft cap uint256 public softcap; // balances for softcap mapping(address => uint) public balancesSoftCap; struct BuyInfo { uint summEth; uint summToken; uint dateEndRefund; } mapping(address => mapping(uint => BuyInfo)) public payments; mapping(address => uint) public paymentCounter; // The token being offered Wolf public token; // start and end timestamps where investments are allowed (both inclusive) // start uint256 public startICO; // end uint256 public endICO; uint256 public period; uint256 public endICO14; // token distribution uint256 public hardCap; uint256 public totalICO; // how many token units a Contributor gets per wei uint256 public rate; // address where funds are collected address public wallet; // minimum/maximum quantity values uint256 public minNumbPerSubscr; uint256 public maxNumbPerSubscr; /** * event for token Procurement logging * @param contributor who Pledged for the tokens * @param beneficiary who got the tokens * @param value weis Contributed for Procurement * @param amount amount of tokens Procured */ event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale() public { token = createTokenContract(); // soft cap softcap = 100 * 1 ether; // minimum quantity values minNumbPerSubscr = 10000000000000000; //0.01 eth maxNumbPerSubscr = 100 * 1 ether; // start and end timestamps where investments are allowed // start startICO = 1521878400;// 03/24/2018 @ 8:00am (UTC) period = 30; // end endICO = startICO + period * 1 days; endICO14 = endICO + 14 * 1 days; // restrictions on amounts during the crowdfunding event stages hardCap = 65000000000 * 1 ether; // rate; rate = 1000000; // address where funds are collected wallet = 0x7472106A07EbAB5a202e195c0dC22776778b44E6; } function setStartICO(uint _startICO) public onlyOwner{ startICO = _startICO; endICO = startICO + period * 1 days; endICO14 = endICO + 14 * 1 days; } function setPeriod(uint _period) public onlyOwner{ period = _period; endICO = startICO + period * 1 days; endICO14 = endICO + 14 * 1 days; } function setRate(uint _rate) public onlyOwner{ rate = _rate; } function createTokenContract() internal returns (Wolf) { return new Wolf(); } // fallback function can be used to Procure tokens function () external payable { procureTokens(msg.sender); } // low level token Pledge function function procureTokens(address beneficiary) public payable { uint256 tokens; uint256 weiAmount = msg.value; uint256 backAmount; require(beneficiary != address(0)); //minimum/maximum amount in ETH require(weiAmount >= minNumbPerSubscr && weiAmount <= maxNumbPerSubscr); if (now >= startICO && now <= endICO && totalICO < hardCap){ tokens = weiAmount.mul(rate); if (hardCap.sub(totalICO) < tokens){ tokens = hardCap.sub(totalICO); weiAmount = tokens.div(rate); backAmount = msg.value.sub(weiAmount); } totalICO = totalICO.add(tokens); } require(tokens > 0); token.mint(beneficiary, tokens); balancesSoftCap[beneficiary] = balancesSoftCap[beneficiary].add(weiAmount); uint256 dateEndRefund = now + 14 * 1 days; paymentCounter[beneficiary] = paymentCounter[beneficiary] + 1; payments[beneficiary][paymentCounter[beneficiary]] = BuyInfo(weiAmount, tokens, dateEndRefund); if (backAmount > 0){ msg.sender.transfer(backAmount); } emit TokenProcurement(msg.sender, beneficiary, weiAmount, tokens); } function refund() public{ require(address(this).balance < softcap && now > endICO); require(balancesSoftCap[msg.sender] > 0); uint value = balancesSoftCap[msg.sender]; balancesSoftCap[msg.sender] = 0; msg.sender.transfer(value); } function revoke(uint _id) public{ require(now <= payments[msg.sender][_id].dateEndRefund); require(payments[msg.sender][_id].summEth > 0); require(payments[msg.sender][_id].summToken > 0); uint value = payments[msg.sender][_id].summEth; uint valueToken = payments[msg.sender][_id].summToken; balancesSoftCap[msg.sender] = balancesSoftCap[msg.sender].sub(value); payments[msg.sender][_id].summEth = 0; payments[msg.sender][_id].summToken = 0; msg.sender.transfer(value); token.burn(msg.sender, valueToken); } function transferToMultisig() public onlyOwner { require(address(this).balance >= softcap && now > endICO14); wallet.transfer(address(this).balance); } }
fallback function can be used to Procure tokens
function () external payable { procureTokens(msg.sender); }
933,134
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../../solidity-utils/contracts/helpers/WordCodec.sol"; import "../BasePoolAuthorization.sol"; import "../interfaces/IBasePoolController.sol"; import "../interfaces/IControlledPool.sol"; /** * @dev Pool controller that serves as the owner of a Balancer pool, and is in turn owned by * an account empowered to make calls on this contract, which are forwarded to the underlyling pool. * * While the owner of the underlying Balancer pool is immutable, ownership of this pool controller * can be transferred, if the corresponding permission is set to allow this operation. To prevent * accidentally setting the manager to an invalid address (and irrevocably losing control of the pool), * transferring ownership is a two-step process. * * If the changeSwapFee permission is enabled, the manager can call setSwapFeePercentage, or delegate * this right to a different address. */ contract BasePoolController is IBasePoolController { using WordCodec for bytes32; // There are three basic pool rights: one for transferring ownership, one for changing the swap fee, // and the last for associating arbitrary metadata with the pool. The remaining BasePool privileged // function (setAssetManagerPoolConfig) has no associated permission. It doesn't make sense to // restrict that, as a fixed configuration would prevent rebalancing and potentially lead to loss // of funds. struct BasePoolRights { bool canTransferOwnership; bool canChangeSwapFee; bool canUpdateMetadata; } // The address empowered to call permissioned functions. address private _manager; // Target of a proposed transfer of ownership. Will be non-zero if there is a transfer pending. // This address must call claimOwnership to complete the transfer. address private _managerCandidate; // Address allowed to call `setSwapFeePercentage`. Initially set to the owner (or 0 if fees are fixed) address private _swapFeeController; // Address of the underlying pool. address public pool; // Immutable controller state - the first 16 bits are reserved as a bitmap for permission flags // (3 used in this base class), and the remaining 240 bits can be used by derived classes to store // any other immutable data. // // [ | 16 bits for permission flags ] // [ 240 bits | 13 bits | 1 bit | 1 bit | 1 bit ] // [ unused | reserved | metadata | swap fee | transfer ] // |MSB LSB| bytes32 internal immutable _controllerState; uint256 private constant _TRANSFER_OWNERSHIP_OFFSET = 0; uint256 private constant _CHANGE_SWAP_FEE_OFFSET = 1; uint256 private constant _UPDATE_METADATA_OFFSET = 2; // Optional metadata associated with this controller (or the pool bound to it) bytes private _metadata; // Event declarations event OwnershipTransferred(address indexed previousManager, address indexed newManager); event SwapFeeControllerChanged(address indexed oldSwapFeeController, address indexed newSwapFeeController); event MetadataUpdated(bytes metadata); // Modifiers // Add this modifier to all functions that call the underlying pool. modifier withBoundPool { _ensurePoolIsBound(); _; } /** * @dev Reverts if called by any account other than the manager. */ modifier onlyManager() { _require(getManager() == msg.sender, Errors.CALLER_IS_NOT_OWNER); _; } /** * @dev Set permissions and the initial manager for the pool controller. We are "trusting" the manager to be * a valid address on deployment, as does BasePool. Transferring ownership to a new manager after deployment * employs a safe, two-step process. */ constructor(bytes32 controllerState, address manager) { _controllerState = controllerState; _manager = manager; // If the swap fee is not fixed, it can be delegated (initially, to the manager). if (controllerState.decodeBool(_CHANGE_SWAP_FEE_OFFSET)) { _swapFeeController = manager; } } /** * @dev Encode the BaseController portion of the controllerState. This is mainly useful for * derived classes to call during construction. */ function encodePermissions(BasePoolRights memory rights) public pure returns (bytes32) { bytes32 permissions; return permissions .insertBool(rights.canTransferOwnership, _TRANSFER_OWNERSHIP_OFFSET) .insertBool(rights.canChangeSwapFee, _CHANGE_SWAP_FEE_OFFSET) .insertBool(rights.canUpdateMetadata, _UPDATE_METADATA_OFFSET); } /** * @dev Getter for the current manager. */ function getManager() public view returns (address) { return _manager; } /** * @dev Returns the manager candidate, which will be non-zero if there is a pending ownership transfer. */ function getManagerCandidate() external view returns (address) { return _managerCandidate; } /** * @dev Getter for the current swap fee controller (0 if fees are fixed). */ function getSwapFeeController() public view returns (address) { return _swapFeeController; } /** * @dev Getter for the transferOwnership permission. */ function canTransferOwnership() public view returns (bool) { return _controllerState.decodeBool(_TRANSFER_OWNERSHIP_OFFSET); } /** * @dev Getter for the canChangeSwapFee permission. */ function canChangeSwapFee() public view returns (bool) { return _controllerState.decodeBool(_CHANGE_SWAP_FEE_OFFSET); } /** * @dev Getter for the canUpdateMetadata permission. */ function canUpdateMetadata() public view returns (bool) { return _controllerState.decodeBool(_UPDATE_METADATA_OFFSET); } /** * @dev The underlying pool owner is immutable, so its address must be known when the pool is deployed. * This means the controller needs to be deployed first. Yet the controller also needs to know the address * of the pool it is controlling. * * We could either pass in a pool factory and have the controller deploy the pool, or have an initialize * function to set the pool address after deployment. This decoupled mechanism seems cleaner. * * It means the pool address must be in storage vs immutable, but this is acceptable for infrequent admin * operations. */ function initialize(address poolAddress) external virtual override { // This can only be called once - and the owner of the pool must be this contract _require( pool == address(0) && BasePoolAuthorization(poolAddress).getOwner() == address(this), Errors.INVALID_INITIALIZATION ); pool = poolAddress; } /** * @dev Stores the proposed new manager in `_managerCandidate`. To prevent accidental transfer to an invalid * address, the candidate address must call `claimOwnership` to complete the transfer. * * Can only be called by the current manager. */ function transferOwnership(address newManager) external onlyManager { _require(canTransferOwnership(), Errors.UNAUTHORIZED_OPERATION); _managerCandidate = newManager; } /** * @dev This must be called by the manager candidate to complete the transferwnership operation. * This "claimable" mechanism prevents accidental transfer of ownership to an invalid address. * * To keep this function simple and focused, transferring ownership does not affect the swapFeeController. * Sometimes the new owner might want to retain the "old" swap fee controller (e.g., if it was * delegated to Gauntlet). Other times an owner may want to take control of fees from the previous * owner. In the latter case, the new owner should call `setSwapFeeController`. */ function claimOwnership() external { address candidate = _managerCandidate; _require(candidate == msg.sender, Errors.SENDER_NOT_ALLOWED); emit OwnershipTransferred(_manager, candidate); _manager = candidate; // Setting the candidate to zero prevents calling this repeatedly and generating multiple redundant events, // and also allows checking (perhaps by a UI) whether there is a pending transfer. _managerCandidate = address(0); } /** * @dev Change the address allowed to call setSwapFeePercentage. */ function setSwapFeeController(address newSwapFeeController) external onlyManager { emit SwapFeeControllerChanged(getSwapFeeController(), newSwapFeeController); _swapFeeController = newSwapFeeController; } /** * @dev Pass a call to BasePool's setSwapFeePercentage through to the underlying pool, if allowed. */ function setSwapFeePercentage(uint256 swapFeePercentage) external virtual override withBoundPool { _require(canChangeSwapFee(), Errors.UNAUTHORIZED_OPERATION); _require(getSwapFeeController() == msg.sender, Errors.SENDER_NOT_ALLOWED); IControlledPool(pool).setSwapFeePercentage(swapFeePercentage); } /** * @dev Pass a call to BasePool's setAssetManagerPoolConfig through to the underlying pool. This does not * need to be permissioned: any pool with asset managers must allow the owner to configure them. */ function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) external virtual override onlyManager withBoundPool { IControlledPool(pool).setAssetManagerPoolConfig(token, poolConfig); } /** * @dev Getter for the optional metadata. */ function getMetadata() public view returns (bytes memory) { return _metadata; } /** * @dev Setter for the admin to set/update the metadata */ function updateMetadata(bytes memory metadata) external onlyManager { _require(canUpdateMetadata(), Errors.UNAUTHORIZED_OPERATION); _metadata = metadata; emit MetadataUpdated(metadata); } function _ensurePoolIsBound() private view { _require(pool != address(0), Errors.UNINITIALIZED_POOL_CONTROLLER); } }
Pass a call to BasePool's setAssetManagerPoolConfig through to the underlying pool. This does not need to be permissioned: any pool with asset managers must allow the owner to configure them./
function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) external virtual override onlyManager withBoundPool { IControlledPool(pool).setAssetManagerPoolConfig(token, poolConfig); }
12,760,425
pragma solidity ^0.4.18; // https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function totalSupply() public view returns (uint supply); function decimals() public view returns(uint digits); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed _from, uint256 _value); } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract Ownable { /// `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require(msg.sender == owner); _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` function Ownable() public { owner = msg.sender; } address newOwner=0x0; event OwnerUpdate(address _prevOwner, address _newOwner); ///change the owner function changeOwner(address _newOwner) public onlyOwner { require(_newOwner != owner); newOwner = _newOwner; } /// accept the ownership function acceptOwnership() public{ require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } } contract Controlled is Ownable{ function Controlled() public { exclude[msg.sender] = true; } modifier onlyAdmin() { if(msg.sender != owner){ require(admins[msg.sender]); } _; } mapping(address => bool) admins; // Flag that determines if the token is transferable or not. bool public transferEnabled = false; // frozen account mapping(address => bool) exclude; mapping(address => bool) locked; mapping(address => bool) public frozenAccount; // The nonce for avoid transfer replay attacks mapping(address => uint256) nonces; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); function setAdmin(address _addr, bool isAdmin) public onlyOwner returns (bool success){ admins[_addr]=isAdmin; return true; } function enableTransfer(bool _enable) public onlyOwner{ transferEnabled=_enable; } function setExclude(address _addr, bool isExclude) public onlyOwner returns (bool success){ exclude[_addr]=isExclude; return true; } function setLock(address _addr, bool isLock) public onlyAdmin returns (bool success){ locked[_addr]=isLock; return true; } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /* * Get the nonce * @param _addr */ function getNonce(address _addr) public constant returns (uint256){ return nonces[_addr]; } modifier transferAllowed(address _addr) { if (!exclude[_addr]) { assert(transferEnabled); assert(!locked[_addr]); assert(!frozenAccount[_addr]); } _; } } contract FeeControlled is Controlled{ // receive transfer fee account address feeReceAccount = 0x0; // transfer rate default value, rate/10000 uint16 defaultTransferRate = 0; // transfer fee min & max uint256 transferFeeMin = 0; uint256 transferFeeMax = 10 ** 10; // transfer rate, rate/10000 mapping(address => int16) transferRates; // reverse transfer rate when receive from user mapping(address => int16) transferReverseRates; function setFeeReceAccount(address _addr) public onlyAdmin returns (bool success){ require(_addr != address(0) && feeReceAccount != _addr); feeReceAccount = _addr; return true; } function setFeeParams(uint16 _transferRate, uint256 _transferFeeMin, uint256 _transferFeeMax) public onlyAdmin returns (bool success){ require(_transferRate>=0 && _transferRate<10000); require(_transferFeeMin>=0 && _transferFeeMin<transferFeeMax); transferFeeMin = _transferFeeMin; transferFeeMax = _transferFeeMax; defaultTransferRate = _transferRate; if(feeReceAccount==0x0){ feeReceAccount = owner; } return true; } function setTransferRate(address[] _addrs, int16 _transferRate) public onlyAdmin returns (bool success){ require((_transferRate>=0 || _transferRate==-1)&& _transferRate<10000); for(uint256 i = 0; i < _addrs.length ; i++){ address _addr = _addrs[i]; transferRates[_addr] = _transferRate; } return true; } function removeTransferRate(address[] _addrs) public onlyAdmin returns (bool success){ for(uint256 i = 0; i < _addrs.length ; i++){ address _addr = _addrs[i]; delete transferRates[_addr]; } return true; } function setReverseRate(address[] _addrs, int16 _reverseRate) public onlyAdmin returns (bool success){ require(_reverseRate>0 && _reverseRate<10000); for(uint256 i = 0; i < _addrs.length ; i++){ address _addr = _addrs[i]; transferReverseRates[_addr] = _reverseRate; } return true; } function removeReverseRate(address[] _addrs) public onlyAdmin returns (bool success){ for(uint256 i = 0; i < _addrs.length ; i++){ address _addr = _addrs[i]; delete transferReverseRates[_addr]; } return true; } function getTransferRate(address _addr) public constant returns(uint16 transferRate){ if(_addr==owner || exclude[_addr] || transferRates[_addr]==-1){ return 0; }else if(transferRates[_addr]==0){ return defaultTransferRate; }else{ return uint16(transferRates[_addr]); } } function getTransferFee(address _addr, uint256 _value) public constant returns(uint256 transferFee){ uint16 transferRate = getTransferRate(_addr); transferFee = 0x0; if(transferRate>0){ transferFee = _value * transferRate / 10000; } if(transferFee<transferFeeMin){ transferFee = transferFeeMin; } if(transferFee>transferFeeMax){ transferFee = transferFeeMax; } return transferFee; } function getReverseRate(address _addr) public constant returns(uint16 reverseRate){ return uint16(transferReverseRates[_addr]); } function getReverseFee(address _addr, uint256 _value) public constant returns(uint256 reverseFee){ uint16 reverseRate = uint16(transferReverseRates[_addr]); reverseFee = 0x0; if(reverseRate>0){ reverseFee = _value * reverseRate / 10000; } if(reverseFee<transferFeeMin){ reverseFee = transferFeeMin; } if(reverseFee>transferFeeMax){ reverseFee = transferFeeMax; } return reverseFee; } } contract TokenERC20 is ERC20, Controlled { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; string public version = 'v1.0'; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; uint256 public allocateEndTime; // This creates an array with all balances mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; function totalSupply() public view returns(uint){ return totalSupply; } function decimals() public view returns(uint){ return decimals; } function balanceOf(address _owner) public view returns(uint){ return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint remaining){ return allowed[_owner][_spender]; } // Allocate tokens to the users // @param _owners The owners list of the token // @param _values The value list of the token function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner { require(allocateEndTime > now); require(_owners.length == _values.length); for(uint256 i = 0; i < _owners.length ; i++){ address to = _owners[i]; uint256 value = _values[i]; require(totalSupply + value > totalSupply && balances[to] + value > balances[to]) ; totalSupply += value; balances[to] += value; } } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) transferAllowed(_from) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Save this for an assertion in the future uint previousBalances = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } /* * Proxy transfer token. When some users of the ethereum account has no ether, * he or she can authorize the agent for broadcast transactions, and agents may charge agency fees * @param _from * @param _to * @param _value * @param feeProxy * @param _v * @param _r * @param _s */ function transferProxy(address _from, address _to, uint256 _value, uint256 _feeProxy, uint8 _v,bytes32 _r, bytes32 _s) public transferAllowed(_from) returns (bool){ require(_value + _feeProxy >= _value); require(balances[_from] >=_value + _feeProxy); uint256 nonce = nonces[_from]; bytes32 h = keccak256(_from,_to,_value,_feeProxy,nonce); require(_from == ecrecover(h,_v,_r,_s)); require(balances[_to] + _value > balances[_to]); require(balances[msg.sender] + _feeProxy > balances[msg.sender]); balances[_from] -= (_value + _feeProxy); balances[_to] += _value; Transfer(_from, _to, _value); if(_feeProxy>0){ balances[msg.sender] += _feeProxy; Transfer(_from, msg.sender, _feeProxy); } nonces[_from] = nonce + 1; return true; } } contract StableToken is TokenERC20, FeeControlled { function transfer(address _to, uint256 _value) public returns (bool success) { return _transferWithRate(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return _transferWithRate(_from, _to, _value); } function _transferWithRate(address _from, address _to, uint256 _value) transferAllowed(_from) internal returns (bool success) { // check transfer rate and transfer fee to owner require(balances[_from] >= _value); uint256 transferFee = getTransferFee(_from, _value); require(balances[_from] >= _value + transferFee); if(msg.sender!=_from){ require(allowed[_from][msg.sender] >= _value + transferFee); } require(balances[_to] + _value > balances[_to]); if(transferFee>0){ require(balances[feeReceAccount] + transferFee > balances[feeReceAccount]); } balances[_from] -= (_value + transferFee); if(msg.sender!=_from){ allowed[_from][msg.sender] -= (_value + transferFee); } balances[_to] += _value; Transfer(_from, _to, _value); if(transferFee>0){ balances[feeReceAccount] += transferFee; Transfer(_from, feeReceAccount, transferFee); } return true; } /* * Proxy transfer token with reverse transfer fee. When some users of the ethereum account has no ether, * he or she can authorize the agent for broadcast transactions, and agents may charge agency fees * @param _from * @param _to, must be reverse address * @param _value * @param fee * @param _v * @param _r * @param _s */ function transferReverseProxy(address _from, address _to, uint256 _value,uint256 _feeProxy, uint8 _v,bytes32 _r, bytes32 _s) public transferAllowed(_from) returns (bool){ require(_feeProxy>=0); require(balances[_from] >= _value + _feeProxy); require(getReverseRate(_to)>0); uint256 nonce = nonces[_from]; bytes32 h = keccak256(_from,_to,_value, _feeProxy, nonce); require(_from == ecrecover(h,_v,_r,_s)); uint256 transferReverseFee = getReverseFee(_to, _value); require(transferReverseFee>0); require(balances[_to] + _value > balances[_to]); require(balances[feeReceAccount] + transferReverseFee > balances[feeReceAccount]); require(balances[msg.sender] + _feeProxy >= balances[msg.sender]); balances[_from] -= (_value + _feeProxy); balances[_to] += (_value - transferReverseFee); balances[feeReceAccount] += transferReverseFee; Transfer(_from, _to, _value); Transfer(_to, feeReceAccount, transferReverseFee); if(_feeProxy>0){ balances[msg.sender] += _feeProxy; Transfer(_from, msg.sender, _feeProxy); } nonces[_from] = nonce + 1; return true; } /* * Proxy transfer token. When some users of the ethereum account has no ether, * he or she can authorize the agent for broadcast transactions, and agents may charge agency fees * @param _from * @param _to * @param _value * @param feeProxy * @param _v * @param _r * @param _s */ function transferProxy(address _from, address _to, uint256 _value, uint256 _feeProxy, uint8 _v,bytes32 _r, bytes32 _s) public transferAllowed(_from) returns (bool){ uint256 transferFee = getTransferFee(_from, _value); require(_value + transferFee + _feeProxy >= _value); require(balances[_from] >=_value + transferFee + _feeProxy); uint256 nonce = nonces[_from]; bytes32 h = keccak256(_from,_to,_value,_feeProxy,nonce); require(_from == ecrecover(h,_v,_r,_s)); require(balances[_to] + _value > balances[_to]); require(balances[msg.sender] + _feeProxy > balances[msg.sender]); balances[_from] -= (_value + transferFee + _feeProxy); balances[_to] += _value; Transfer(_from, _to, _value); if(_feeProxy>0){ balances[msg.sender] += _feeProxy; Transfer(_from, msg.sender, _feeProxy); } if(transferFee>0){ balances[feeReceAccount] += transferFee; Transfer(_from, feeReceAccount, transferFee); } nonces[_from] = nonce + 1; return true; } /* * Wrapper function: transferProxy + transferReverseProxy * address[] _addrs => [_from, _origin, _to] * uint256[] _values => [_value, _feeProxy] * token flows * _from->_origin: _value * _from->sender: _feeProxy * _origin->_to: _value * _to->feeAccount: transferFee * _from sign: * (_v[0],_r[0],_s[0]) = sign(_from, _origin, _value, _feeProxy, nonces[_from]) * _origin sign: * (_v[1],_r[1],_s[1]) = sign(_origin, _to, _value) */ function transferReverseProxyThirdParty(address[] _addrs, uint256[] _values, uint8[] _v, bytes32[] _r, bytes32[] _s) public transferAllowed(_addrs[0]) returns (bool){ address _from = _addrs[0]; address _origin = _addrs[1]; address _to = _addrs[2]; uint256 _value = _values[0]; uint256 _feeProxy = _values[1]; require(_feeProxy>=0); require(balances[_from] >= (_value + _feeProxy)); require(getReverseRate(_to)>0); uint256 transferReverseFee = getReverseFee(_to, _value); require(transferReverseFee>0); // check sign _from => _origin uint256 nonce = nonces[_from]; bytes32 h = keccak256(_from, _origin, _value, _feeProxy, nonce); require(_from == ecrecover(h,_v[0],_r[0],_s[0])); // check sign _origin => _to bytes32 h1 = keccak256(_origin, _to, _value); require(_origin == ecrecover(h1,_v[1],_r[1],_s[1])); require(balances[_to] + _value > balances[_to]); require(balances[feeReceAccount] + transferReverseFee > balances[feeReceAccount]); require(balances[msg.sender] + _feeProxy >= balances[msg.sender]); balances[_from] -= _value + _feeProxy; balances[_to] += (_value - transferReverseFee); balances[feeReceAccount] += transferReverseFee; Transfer(_from, _origin, _value); Transfer(_origin, _to, _value); Transfer(_to, feeReceAccount, transferReverseFee); if(_feeProxy>0){ balances[msg.sender] += _feeProxy; Transfer(_from, msg.sender, _feeProxy); } nonces[_from] = nonce + 1; return true; } /* * Proxy approve that some one can authorize the agent for broadcast transaction * which call approve method, and agents may charge agency fees * @param _from The address which should tranfer TOKEN to others * @param _spender The spender who allowed by _from * @param _value The value that should be tranfered. * @param _v * @param _r * @param _s */ function approveProxy(address _from, address _spender, uint256 _value, uint8 _v,bytes32 _r, bytes32 _s) public returns (bool success) { uint256 nonce = nonces[_from]; bytes32 hash = keccak256(_from,_spender,_value,nonce); require(_from == ecrecover(hash,_v,_r,_s)); allowed[_from][_spender] = _value; Approval(_from, _spender, _value); nonces[_from] = nonce + 1; return true; } } contract HanYinToken is StableToken{ function HanYinToken() public { name = "HanYin stable Token"; decimals = 6; symbol = "HYT"; version = 'v1.0'; allocateEndTime = now + 1 days; setFeeParams(100, 0, 1000000000000); } }
check transfer rate and transfer fee to owner
function _transferWithRate(address _from, address _to, uint256 _value) transferAllowed(_from) internal returns (bool success) { require(balances[_from] >= _value); uint256 transferFee = getTransferFee(_from, _value); require(balances[_from] >= _value + transferFee); if(msg.sender!=_from){ require(allowed[_from][msg.sender] >= _value + transferFee); } require(balances[_to] + _value > balances[_to]); if(transferFee>0){ require(balances[feeReceAccount] + transferFee > balances[feeReceAccount]); } balances[_from] -= (_value + transferFee); if(msg.sender!=_from){ allowed[_from][msg.sender] -= (_value + transferFee); } balances[_to] += _value; Transfer(_from, _to, _value); if(transferFee>0){ balances[feeReceAccount] += transferFee; Transfer(_from, feeReceAccount, transferFee); } return true; }
15,862,104
./full_match/1/0x9b2Dc6e830320C48044a555263cBA4CdeB0FB201/sources/contracts/DeHiveTokensale.sol
Updates public sales pool maximum _publicPool New public pool DHV maximum value/
function adminSetPublicPool(uint256 _publicPool) external onlyOwner { PUBLIC_SALE_DHV_POOL = _publicPool; }
3,125,513
/* DVIP Terms of Service The following Terms of Service specify the agreement between Decentralized Capital Ltd. (DC) and the purchaser of DVIP Memberships (customer/member). By purchasing, using, or possessing the DVIP token you agree to be legally bound by these terms, which shall take effect immediately upon purchase of the membership. 1. Rights of DVIP Membership holders: Each membership entitles the customer to ZERO transaction fees on all on-chain transfers of DC Assets, and ½ off fees for purchasing and redeeming DC Assets through Crypto Capital. DVIP also entitles the customer to discounts on select future Decentralized Capital Ltd. services. These discounts only apply to the fees specified on the DC website. DC is not responsible for any fees charged by third parties including, but not limited to, dapps, exchanges, Crypto Capital, and Coinapult. 2. DVIP membership rights expire on January 1st, 2020. Upon expiration of membership benefits, each 1/100th of a token is redeemable for an additional $1.50 in fees on eligible DC products. This additional discount expires on January 1st, 2022. 3. Customers can purchase more than one membership, but only one membership can be active at a time for any one wallet. Under no circumstances are members eligible for a refund on the DVIP purchase. 4. DVIP tokens are not equity in Decentralized Capital ltd. and do not give holders any power over Decentralized Capital ltd. including, but not limited to, shareholder voting, a claim on assets, or input into how Decentralized Capital ltd. is governed and managed. 5. Possession of the DVIP token operates as proof of membership, and DVIP tokens can be transferred to any other wallet on Ethereum. If the DVIP token is transferred to a 3rd party, the membership benefits no longer pertain to the original party. In the event of a transfer, membership benefits will apply only AFTER a one week incubation period; any withdrawal initiated prior to the end of this incubation period will be charged the standard transaction fee. DC reserves the right to adjust the duration of the incubation period; the incubation period will never be more than one month. Changes to the DVIP balance will reset the incubation period for any DVIP that is not fully incubated. Active DVIP is not affected by balance changes. 6. DVIP membership benefits are only available to individual users. Platforms such as exchanges and dapps can hold DVIP, but the transaction fee discounts specified in section 1 will not apply. 7. Membership benefits are executed via the DC smart contract system; the DC membership must be held in the wallet used for DC Asset transactions in order for the discounts to apply. No transaction fees will be waived for members who receive transactions using a wallet that does not hold their DVIP tokens. 8. In the event of bankruptcy: DVIP is valid until January 1st, 2020. In the event that Decentralized Capital Ltd. ceases operations, DVIP does not represent any claim on company assets nor does Decentralized Capital Ltd. have any further commitment to holders of DVIP, such as a refund on the purchase of the DVIP. 9. Future Sale of DVIP: Total DVIP supply is capped at 2,000, 1,500 of which are available for purchase during this initial sale. Any DVIP not sold in the initial membership sale will be destroyed, further reducing the total supply of DVIP. The remaining 500 memberships will be sold at a later date. 10. DVIP Buyback Rights: Decentralized Capital Ltd. reserves the right to repurchase the DVIP from token holders at any time. Repurchase will occur at the average price of all markets where DVIP is listed. 11. Entire Agreement. The foregoing Membership Terms & Conditions contain the entire terms and agreements in connection with Member's participation in the DC service and no representations, inducements, promises or agreement, or otherwise, between DC and the Member not included herein, shall be of any force or effect. If any of the foregoing terms or provisions shall be invalid or unenforceable, the remaining terms and provisions hereof shall not be affected. 12. This agreement shall be governed by and construed under, and the legal relations among the parties hereto shall be determined in accordance with, the laws of the United Kingdom of Great Britain and Northern Ireland. */ contract Assertive { function assert(bool assertion) { if (!assertion) throw; } } contract Owned is Assertive { address public owner; event SetOwner(address indexed previousOwner, address indexed newOwner); function Owned () { owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _ } function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } } contract StateTransferrable is Owned { bool internal locked; event Locked(address indexed from); event PropertySet(address indexed from); modifier onlyIfUnlocked { assert(!locked); _ } modifier setter { _ PropertySet(msg.sender); } modifier onlyOwnerUnlocked { assert(!locked && msg.sender == owner); _ } function lock() onlyOwner onlyIfUnlocked { locked = true; Locked(msg.sender); } function isLocked() returns (bool status) { return locked; } } contract TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract Relay { function relayReceiveApproval(address _caller, address _spender, uint256 _amount, bytes _extraData) returns (bool success); } contract TokenBase is Owned { bytes32 public standard = 'Token 0.1'; bytes32 public name; bytes32 public symbol; bool public allowTransactions; uint256 public totalSupply; event Approval(address indexed from, address indexed spender, uint256 amount); mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function () { throw; } } contract TrustEvents { event AuthInit(address indexed from); event AuthComplete(address indexed from, address indexed with); event AuthPending(address indexed from); event Unauthorized(address indexed from); event InitCancel(address indexed from); event NothingToCancel(address indexed from); event SetMasterKey(address indexed from); event AuthCancel(address indexed from, address indexed with); } contract Trust is StateTransferrable, TrustEvents { mapping (address => bool) public masterKeys; mapping (address => bytes32) public nameRegistry; address[] public masterKeyIndex; mapping (address => bool) public masterKeyActive; mapping (address => bool) public trustedClients; mapping (uint256 => address) public functionCalls; mapping (address => uint256) public functionCalling; /* --------------- modifiers --------------*/ modifier multisig (bytes32 hash) { if (!masterKeys[msg.sender]) { Unauthorized(msg.sender); } else if (functionCalling[msg.sender] == 0) { if (functionCalls[uint256(hash)] == 0x0) { functionCalls[uint256(hash)] = msg.sender; functionCalling[msg.sender] = uint256(hash); AuthInit(msg.sender); } else { AuthComplete(functionCalls[uint256(hash)], msg.sender); resetAction(uint256(hash)); _ } } else { AuthPending(msg.sender); } } /* --------------- setter methods, only for the unlocked state --------------*/ /** * @notice Sets a master key * * @param addr Address */ function setMasterKey(address addr) onlyOwnerUnlocked { assert(!masterKeys[addr]); activateMasterKey(addr); masterKeys[addr] = true; SetMasterKey(msg.sender); } /** * @notice Adds a trusted client * * @param addr Address */ function setTrustedClient(address addr) onlyOwnerUnlocked setter { trustedClients[addr] = true; } /* --------------- methods to be called by a Master Key --------------*/ /* --------------- multisig admin methods --------------*/ /** * @notice remove contract `addr` from the list of trusted contracts * * @param addr Address of client contract to be removed */ function untrustClient(address addr) multisig(sha3(msg.data)) { trustedClients[addr] = false; } /** * @notice add contract `addr` to the list of trusted contracts * * @param addr Address of contract to be added */ function trustClient(address addr) multisig(sha3(msg.data)) { trustedClients[addr] = true; } /** * @notice remove key `addr` to the list of master keys * * @param addr Address of the masterkey */ function voteOutMasterKey(address addr) multisig(sha3(msg.data)) { assert(masterKeys[addr]); masterKeys[addr] = false; } /** * @notice add key `addr` to the list of master keys * * @param addr Address of the masterkey */ function voteInMasterKey(address addr) multisig(sha3(msg.data)) { assert(!masterKeys[addr]); activateMasterKey(addr); masterKeys[addr] = true; } /* --------------- methods to be called by Trusted Client Contracts --------------*/ /** * @notice Cancel outstanding multisig method call from address `from`. Called from trusted clients. * * @param from Address that issued the call that needs to be cancelled */ function authCancel(address from) external returns (uint8 status) { if (!masterKeys[from] || !trustedClients[msg.sender]) { Unauthorized(from); return 0; } uint256 call = functionCalling[from]; if (call == 0) { NothingToCancel(from); return 1; } else { AuthCancel(from, from); functionCalling[from] = 0; functionCalls[call] = 0x0; return 2; } } /** * @notice Authorize multisig call on a trusted client. Called from trusted clients. * * @param from Address from which call is made. * @param hash of method call */ function authCall(address from, bytes32 hash) external returns (uint8 code) { if (!masterKeys[from] || !trustedClients[msg.sender]) { Unauthorized(from); return 0; } if (functionCalling[from] == 0) { if (functionCalls[uint256(hash)] == 0x0) { functionCalls[uint256(hash)] = from; functionCalling[from] = uint256(hash); AuthInit(from); return 1; } else { AuthComplete(functionCalls[uint256(hash)], from); resetAction(uint256(hash)); return 2; } } else { AuthPending(from); return 3; } } /* --------------- methods to be called directly on the contract --------------*/ /** * @notice cancel any outstanding multisig call * */ function cancel() returns (uint8 code) { if (!masterKeys[msg.sender]) { Unauthorized(msg.sender); return 0; } uint256 call = functionCalling[msg.sender]; if (call == 0) { NothingToCancel(msg.sender); return 1; } else { AuthCancel(msg.sender, msg.sender); uint256 hash = functionCalling[msg.sender]; functionCalling[msg.sender] = 0x0; functionCalls[hash] = 0; return 2; } } /* --------------- private methods --------------*/ function resetAction(uint256 hash) internal { address addr = functionCalls[hash]; functionCalls[hash] = 0x0; functionCalling[addr] = 0; } function activateMasterKey(address addr) internal { if (!masterKeyActive[addr]) { masterKeyActive[addr] = true; masterKeyIndex.push(addr); } } /* --------------- helper methods for siphoning --------------*/ function extractMasterKeyIndexLength() returns (uint256 length) { return masterKeyIndex.length; } } contract TrustClient is StateTransferrable, TrustEvents { address public trustAddress; modifier multisig (bytes32 hash) { assert(trustAddress != address(0x0)); address current = Trust(trustAddress).functionCalls(uint256(hash)); uint8 code = Trust(trustAddress).authCall(msg.sender, hash); if (code == 0) Unauthorized(msg.sender); else if (code == 1) AuthInit(msg.sender); else if (code == 2) { AuthComplete(current, msg.sender); _ } else if (code == 3) { AuthPending(msg.sender); } } function setTrust(address addr) setter onlyOwnerUnlocked { trustAddress = addr; } function cancel() returns (uint8 status) { assert(trustAddress != address(0x0)); uint8 code = Trust(trustAddress).authCancel(msg.sender); if (code == 0) Unauthorized(msg.sender); else if (code == 1) NothingToCancel(msg.sender); else if (code == 2) AuthCancel(msg.sender, msg.sender); return code; } } contract DVIPBackend { uint8 public decimals; function assert(bool assertion) { if (!assertion) throw; } bytes32 public standard = 'Token 0.1'; bytes32 public name; bytes32 public symbol; bool public allowTransactions; uint256 public totalSupply; event Approval(address indexed from, address indexed spender, uint256 amount); event PropertySet(address indexed from); mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* mapping (address => bool) public balanceOfActive; address[] public balanceOfIndex; */ /* mapping (address => bool) public allowanceActive; address[] public allowanceIndex; mapping (address => mapping (address => bool)) public allowanceRecordActive; mapping (address => address[]) public allowanceRecordIndex; */ event Transfer(address indexed from, address indexed to, uint256 value); uint256 public baseFeeDivisor; uint256 public feeDivisor; uint256 public singleDVIPQty; function () { throw; } bool public locked; address public owner; modifier onlyOwnerUnlocked { assert(msg.sender == owner && !locked); _ } modifier onlyOwner { assert(msg.sender == owner); _ } function lock() onlyOwnerUnlocked returns (bool success) { locked = true; PropertySet(msg.sender); return true; } function setOwner(address _address) onlyOwner returns (bool success) { owner = _address; PropertySet(msg.sender); return true; } uint256 public expiry; uint8 public feeDecimals; struct Validity { uint256 last; uint256 ts; } mapping (address => Validity) public validAfter; uint256 public mustHoldFor; address public hotwalletAddress; address public frontendAddress; mapping (address => bool) public frozenAccount; /* mapping (address => bool) public frozenAccountActive; address[] public frozenAccountIndex; */ mapping (address => uint256) public exportFee; /* mapping (address => bool) public exportFeeActive; address[] public exportFeeIndex; */ event FeeSetup(address indexed from, address indexed target, uint256 amount); event Processed(address indexed sender); modifier onlyAsset { if (msg.sender != frontendAddress) throw; _ } /** * Constructor. * */ function DVIPBackend(address _hotwalletAddress, address _frontendAddress) { owner = msg.sender; hotwalletAddress = _hotwalletAddress; frontendAddress = _frontendAddress; allowTransactions = true; totalSupply = 0; name = "DVIP"; symbol = "DVIP"; feeDecimals = 6; decimals = 1; expiry = 1514764800; //1 jan 2018 mustHoldFor = 604800; precalculate(); } function setHotwallet(address _address) onlyOwnerUnlocked { hotwalletAddress = _address; PropertySet(msg.sender); } function setFrontend(address _address) onlyOwnerUnlocked { frontendAddress = _address; PropertySet(msg.sender); } /** * @notice Transfer `_amount` from `msg.sender.address()` to `_to`. * * @param _to Address that will receive. * @param _amount Amount to be transferred. */ function transfer(address caller, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(balanceOf[caller] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(!frozenAccount[caller]); assert(!frozenAccount[_to]); balanceOf[caller] -= _amount; // activateBalance(caller); // activateBalance(_to); uint256 preBalance = balanceOf[_to]; balanceOf[_to] += _amount; bool alreadyMax = preBalance >= singleDVIPQty; if (!alreadyMax) { if (now >= validAfter[_to].ts + mustHoldFor) validAfter[_to].last = preBalance; validAfter[_to].ts = now; } if (validAfter[caller].last > balanceOf[caller]) validAfter[caller].last = balanceOf[caller]; Transfer(caller, _to, _amount); return true; } /** * @notice Transfer `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */ function transferFrom(address caller, address _from, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(balanceOf[_from] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(_amount <= allowance[_from][caller]); assert(!frozenAccount[caller]); assert(!frozenAccount[_from]); assert(!frozenAccount[_to]); balanceOf[_from] -= _amount; uint256 preBalance = balanceOf[_to]; balanceOf[_to] += _amount; // activateBalance(_from); // activateBalance(_to); allowance[_from][caller] -= _amount; bool alreadyMax = preBalance >= singleDVIPQty; if (!alreadyMax) { if (now >= validAfter[_to].ts + mustHoldFor) validAfter[_to].last = preBalance; validAfter[_to].ts = now; } if (validAfter[_from].last > balanceOf[_from]) validAfter[_from].last = balanceOf[_from]; Transfer(_from, _to, _amount); return true; } /** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same transcation. * @return result of the method call */ function approveAndCall(address caller, address _spender, uint256 _amount, bytes _extraData) onlyAsset returns (bool success) { assert(allowTransactions); allowance[caller][_spender] = _amount; // activateAllowance(caller, _spender); Relay(frontendAddress).relayReceiveApproval(caller, _spender, _amount, _extraData); Approval(caller, _spender, _amount); return true; } /** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @return result of the method call */ function approve(address caller, address _spender, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); allowance[caller][_spender] = _amount; // activateAllowance(caller, _spender); Approval(caller, _spender, _amount); return true; } /* --------------- multisig admin methods --------------*/ /** * @notice Sets the expiry time in milliseconds since 1970. * * @param ts milliseconds since 1970. * */ function setExpiry(uint256 ts) onlyOwner { expiry = ts; Processed(msg.sender); } /** * @notice Mints `mintedAmount` new tokens to the hotwallet `hotWalletAddress`. * * @param mintedAmount Amount of new tokens to be minted. */ function mint(uint256 mintedAmount) onlyOwner { balanceOf[hotwalletAddress] += mintedAmount; // activateBalance(hotwalletAddress); totalSupply += mintedAmount; Processed(msg.sender); } function freezeAccount(address target, bool frozen) onlyOwner { frozenAccount[target] = frozen; // activateFrozenAccount(target); Processed(msg.sender); } function seizeTokens(address target, uint256 amount) onlyOwner { assert(balanceOf[target] >= amount); assert(frozenAccount[target]); balanceOf[target] -= amount; balanceOf[hotwalletAddress] += amount; Transfer(target, hotwalletAddress, amount); } function destroyTokens(uint256 amt) onlyOwner { assert(balanceOf[hotwalletAddress] >= amt); balanceOf[hotwalletAddress] -= amt; Processed(msg.sender); } /** * @notice Sets an export fee of `fee` on address `addr` * * @param addr Address for which the fee is valid * @param addr fee Fee * */ function setExportFee(address addr, uint256 fee) onlyOwner { exportFee[addr] = fee; // activateExportFee(addr); Processed(msg.sender); } function setHoldingPeriod(uint256 ts) onlyOwner { mustHoldFor = ts; Processed(msg.sender); } function setAllowTransactions(bool allow) onlyOwner { allowTransactions = allow; Processed(msg.sender); } /* --------------- fee calculation method ---------------- */ /** * @notice 'Returns the fee for a transfer from `from` to `to` on an amount `amount`. * * Fee's consist of a possible * - import fee on transfers to an address * - export fee on transfers from an address * DVIP ownership on an address * - reduces fee on a transfer from this address to an import fee-ed address * - reduces the fee on a transfer to this address from an export fee-ed address * DVIP discount does not work for addresses that have an import fee or export fee set up against them. * * DVIP discount goes up to 100% * * @param from From address * @param to To address * @param amount Amount for which fee needs to be calculated. * */ function feeFor(address from, address to, uint256 amount) constant external returns (uint256 value) { uint256 fee = exportFee[from]; if (fee == 0) return 0; if (now >= expiry) return amount*fee / baseFeeDivisor; uint256 amountHeld; if (balanceOf[to] != 0) { if (validAfter[to].ts + mustHoldFor < now) amountHeld = balanceOf[to]; else amountHeld = validAfter[to].last; if (amountHeld >= singleDVIPQty) return 0; return amount*fee*(singleDVIPQty - amountHeld) / feeDivisor; } else return amount*fee / baseFeeDivisor; } function precalculate() internal returns (bool success) { baseFeeDivisor = pow10(1, feeDecimals); feeDivisor = pow10(1, feeDecimals + decimals); singleDVIPQty = pow10(1, decimals); } function div10(uint256 a, uint8 b) internal returns (uint256 result) { for (uint8 i = 0; i < b; i++) { a /= 10; } return a; } function pow10(uint256 a, uint8 b) internal returns (uint256 result) { for (uint8 i = 0; i < b; i++) { a *= 10; } return a; } /* function activateBalance(address address_) internal { if (!balanceOfActive[address_]) { balanceOfActive[address_] = true; balanceOfIndex.push(address_); } } function activateFrozenAccount(address address_) internal { if (!frozenAccountActive[address_]) { frozenAccountActive[address_] = true; frozenAccountIndex.push(address_); } } function activateAllowance(address from, address to) internal { if (!allowanceActive[from]) { allowanceActive[from] = true; allowanceIndex.push(from); } if (!allowanceRecordActive[from][to]) { allowanceRecordActive[from][to] = true; allowanceRecordIndex[from].push(to); } } function activateExportFee(address address_) internal { if (!exportFeeActive[address_]) { exportFeeActive[address_] = true; exportFeeIndex.push(address_); } } function extractBalanceOfLength() constant returns (uint256 length) { return balanceOfIndex.length; } function extractAllowanceLength() constant returns (uint256 length) { return allowanceIndex.length; } function extractAllowanceRecordLength(address from) constant returns (uint256 length) { return allowanceRecordIndex[from].length; } function extractFrozenAccountLength() constant returns (uint256 length) { return frozenAccountIndex.length; } function extractFeeLength() constant returns (uint256 length) { return exportFeeIndex.length; } */ } /** * @title DVIP * * @author Raymond Pulver IV * */ contract DVIP is TokenBase, StateTransferrable, TrustClient, Relay { address public backendContract; /** * Constructor * * */ function DVIP(address _backendContract) { backendContract = _backendContract; } function standard() constant returns (bytes32 std) { return DVIPBackend(backendContract).standard(); } function name() constant returns (bytes32 nm) { return DVIPBackend(backendContract).name(); } function symbol() constant returns (bytes32 sym) { return DVIPBackend(backendContract).symbol(); } function decimals() constant returns (uint8 precision) { return DVIPBackend(backendContract).decimals(); } function allowance(address from, address to) constant returns (uint256 res) { return DVIPBackend(backendContract).allowance(from, to); } /* --------------- multisig admin methods --------------*/ /** * @notice Sets the backend contract to `_backendContract`. Can only be switched by multisig. * * @param _backendContract Address of the underlying token contract. */ function setBackend(address _backendContract) multisig(sha3(msg.data)) { backendContract = _backendContract; } function setBackendOwner(address _backendContract) onlyOwnerUnlocked { backendContract = _backendContract; } /* --------------- main token methods --------------*/ /** * @notice Returns the balance of `_address`. * * @param _address The address of the balance. */ function balanceOf(address _address) constant returns (uint256 balance) { return DVIPBackend(backendContract).balanceOf(_address); } /** * @notice Returns the total supply of the token * */ function totalSupply() constant returns (uint256 balance) { return DVIPBackend(backendContract).totalSupply(); } /** * @notice Transfer `_amount` to `_to`. * * @param _to Address that will receive. * @param _amount Amount to be transferred. */ function transfer(address _to, uint256 _amount) returns (bool success) { if (!DVIPBackend(backendContract).transfer(msg.sender, _to, _amount)) throw; Transfer(msg.sender, _to, _amount); return true; } /** * @notice Approve Approves spender `_spender` to transfer `_amount`. * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same transcation. * @return result of the method call */ function approveAndCall(address _spender, uint256 _amount, bytes _extraData) returns (bool success) { if (!DVIPBackend(backendContract).approveAndCall(msg.sender, _spender, _amount, _extraData)) throw; Approval(msg.sender, _spender, _amount); return true; } /** * @notice Approve Approves spender `_spender` to transfer `_amount`. * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @return result of the method call */ function approve(address _spender, uint256 _amount) returns (bool success) { if (!DVIPBackend(backendContract).approve(msg.sender, _spender, _amount)) throw; Approval(msg.sender, _spender, _amount); return true; } /** * @notice Transfer `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */ function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { if (!DVIPBackend(backendContract).transferFrom(msg.sender, _from, _to, _amount)) throw; Transfer(_from, _to, _amount); return true; } /** * @notice Returns fee for transferral of `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return height of the fee */ function feeFor(address _from, address _to, uint256 _amount) constant returns (uint256 amount) { return DVIPBackend(backendContract).feeFor(_from, _to, _amount); } /* --------------- to be called by backend --------------*/ function relayReceiveApproval(address _caller, address _spender, uint256 _amount, bytes _extraData) returns (bool success) { assert(msg.sender == backendContract); TokenRecipient spender = TokenRecipient(_spender); spender.receiveApproval(_caller, _amount, this, _extraData); return true; } }
Approve Approves spender `_spender` to transfer `_amount`. _spender Address that receives the cheque _amount Amount on the cheque return result of the method call/
function approve(address _spender, uint256 _amount) returns (bool success) { if (!DVIPBackend(backendContract).approve(msg.sender, _spender, _amount)) throw; Approval(msg.sender, _spender, _amount); return true; }
15,801,746
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[email protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[email protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[email protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[email protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[email protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) { if (_y > 3) { z_ = _y; uint256 x = _y / 2 + 1; while (x < z_) { z_ = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z_ = 1; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[email protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[email protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @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) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev 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) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @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) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[email protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[email protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[email protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[email protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[email protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[email protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[email protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[email protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
Configure the extensions of a fund _feeManagerConfigData Encoded config for fees to enable _policyManagerConfigData Encoded config for policies to enable No need to assert anything beyond FundDeployer access. Called atomically with init(), but after ComptrollerLib has been deployed, giving access to its state and interface
function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } }
1,696,827
./partial_match/1/0x8D35372EA3E85C49A60F0A72EdeFF8629dA3999A/sources/TrueFiPool2.sol
Return pool credit line value return pool credit value/
function creditValue() public view returns (uint256) { if (address(creditAgency) == address(0)) { return 0; } return creditAgency.poolCreditValue(ITrueFiPool2(this)); }
2,698,369
//Address: 0x880d6adb5bb4c8a7f578d31a4ddb0c48bc590fa3 //Contract name: Steak //Balance: 0 Ether //Verification Date: 8/25/2017 //Transacion Count: 13 // CODE STARTS HERE pragma solidity ^0.4.15; /** * * STEAK TOKEN (BOV) * * Make bank by eating flank. See https://steaktoken.com. * */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title 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; modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract SteakToken is Ownable { using SafeMath for uint256; string public name = "Steak Token"; string public symbol = "BOV"; uint public decimals = 18; uint public totalSupply; // Total BOV in circulation. mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed ownerAddress, address indexed spenderAddress, uint256 value); event Mint(address indexed to, uint256 amount); event MineFinished(); function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool) { if(msg.data.length < (2 * 32) + 4) { revert(); } // protect against short address attack balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } } /** * @title AuctionCrowdsale * @dev The owner starts and ends the crowdsale manually. * Players can make token purchases during the crowdsale * and their tokens can be claimed after the sale ends. * Players receive an amount proportional to their investment. */ contract AuctionCrowdsale is SteakToken { using SafeMath for uint; uint public initialSale; // Amount of BOV tokens being sold during crowdsale. bool public saleStarted; bool public saleEnded; uint public absoluteEndBlock; // Anybody can end the crowdsale and trigger token distribution if beyond this block number. uint256 public weiRaised; // Total amount raised in crowdsale. address[] public investors; // Investor addresses uint public numberOfInvestors; mapping(address => uint256) public investments; // How much each address has invested. mapping(address => bool) public claimed; // Keep track of whether each investor has been awarded their BOV tokens. bool public bovBatchDistributed; // TODO: this can be removed with manual crowdsale end-time uint public initialPrizeWeiValue; // The first steaks mined will be awarded BOV equivalent to this ETH value. Set in Steak() initializer. uint public initialPrizeBov; // Initial mining prize in BOV units. Set in endCrowdsale() or endCrowdsalePublic(). uint public dailyHashExpires; // When the dailyHash expires. Will be roughly around 3am EST. /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event TokenInvestment(address indexed purchaser, address indexed beneficiary, uint256 value); // Sending ETH to this contract's address registers the investment. function () payable { invest(msg.sender); } // Participate in the crowdsale. // Records how much each address has invested. function invest(address beneficiary) payable { require(beneficiary != 0x0); require(validInvestment()); uint256 weiAmount = msg.value; uint investedAmount = investments[beneficiary]; forwardFunds(); if (investedAmount > 0) { // If they've already invested, increase their balance. investments[beneficiary] = investedAmount + weiAmount; // investedAmount.add(weiAmount); } else { // If new investor investors.push(beneficiary); numberOfInvestors += 1; investments[beneficiary] = weiAmount; } weiRaised = weiRaised.add(weiAmount); TokenInvestment(msg.sender, beneficiary, weiAmount); } // @return true if the transaction can invest function validInvestment() internal constant returns (bool) { bool withinPeriod = saleStarted && !saleEnded; bool nonZeroPurchase = (msg.value > 0); return withinPeriod && nonZeroPurchase; } // Distribute 10M tokens proportionally amongst all investors. Can be called by anyone after the crowdsale ends. // ClaimTokens() can be run by individuals to claim their tokens. function distributeAllTokens() public { require(!bovBatchDistributed); require(crowdsaleHasEnded()); // Allocate BOV proportionally to each investor. for (uint i=0; i < numberOfInvestors; i++) { address investorAddr = investors[i]; if (!claimed[investorAddr]) { // If the investor hasn't already claimed their BOV. claimed[investorAddr] = true; uint amountInvested = investments[investorAddr]; uint bovEarned = amountInvested.mul(initialSale).div(weiRaised); mint(investorAddr, bovEarned); } } bovBatchDistributed = true; } // Claim your BOV; allocates BOV proportionally to this investor. // Can be called by investors to claim their BOV after the crowdsale ends. // distributeAllTokens() is a batch alternative to this. function claimTokens(address origAddress) public { require(crowdsaleHasEnded()); require(claimed[origAddress] == false); uint amountInvested = investments[origAddress]; uint bovEarned = amountInvested.mul(initialSale).div(weiRaised); claimed[origAddress] = true; mint(origAddress, bovEarned); } // Investors: see how many BOV you are currently entitled to (before the end of the crowdsale and distribution of tokens). function getCurrentShare(address addr) public constant returns (uint) { require(!bovBatchDistributed && !claimed[addr]); // Tokens cannot have already been distributed. uint amountInvested = investments[addr]; uint currentBovShare = amountInvested.mul(initialSale).div(weiRaised); return currentBovShare; } // send ether to the fund collection wallet function forwardFunds() internal { owner.transfer(msg.value); } // The owner manually starts the crowdsale at a pre-determined time. function startCrowdsale() onlyOwner { require(!saleStarted && !saleEnded); saleStarted = true; } // endCrowdsale() and endCrowdsalePublic() moved to Steak contract // Normally, the owner will end the crowdsale at the pre-determined time. function endCrowdsale() onlyOwner { require(saleStarted && !saleEnded); dailyHashExpires = now; // Will end crowdsale at 3am EST, so expiration time will roughly be around 3am. saleEnded = true; setInitialPrize(); } // Normally, Madame BOV ends the crowdsale at the pre-determined time, but if Madame BOV fails to do so, anybody can trigger endCrowdsalePublic() after absoluteEndBlock. function endCrowdsalePublic() public { require(block.number > absoluteEndBlock); require(saleStarted && !saleEnded); dailyHashExpires = now; saleEnded = true; setInitialPrize(); } // Calculate initial mining prize (0.0357 ether's worth of BOV). This is called in endCrowdsale(). function setInitialPrize() internal returns (uint) { require(crowdsaleHasEnded()); require(initialPrizeBov == 0); // Can only be set once uint tokenUnitsPerWei = initialSale.div(weiRaised); initialPrizeBov = tokenUnitsPerWei.mul(initialPrizeWeiValue); return initialPrizeBov; } // @return true if crowdsale event has ended function crowdsaleHasEnded() public constant returns (bool) { return saleStarted && saleEnded; } function getInvestors() public returns (address[]) { return investors; } } contract Steak is AuctionCrowdsale { // using SafeMath for uint; bytes32 public dailyHash; // The last five digits of the dailyHash must be included in steak pictures. Submission[] public submissions; // All steak pics uint public numSubmissions; Submission[] public approvedSubmissions; mapping (address => uint) public memberId; // Get member ID from address. Member[] public members; // Index is memberId uint public halvingInterval; // BOV award is halved every x steaks uint public numberOfHalvings; // How many times the BOV reward per steak is halved before it returns 0. uint public lastMiningBlock; // No mining after this block. Set in initializer. bool public ownerCredited; // Has the owner been credited BOV yet? event PicAdded(address msgSender, uint submissionID, address recipient, bytes32 propUrl); // Need msgSender so we can watch for this event. event Judged(uint submissionID, bool position, address voter, bytes32 justification); event MembershipChanged(address member, bool isMember); struct Submission { address recipient; // Would-be BOV recipient bytes32 url; // IMGUR url; 32-char max bool judged; // Has an admin voted? bool submissionApproved;// Has it been approved? address judgedBy; // Admin who judged this steak bytes32 adminComments; // Admin should leave feedback on non-approved steaks. 32-char max. bytes32 todaysHash; // The hash in the image should match this hash. uint awarded; // Amount awarded } // Members can vote on steak struct Member { address member; bytes32 name; uint memberSince; } modifier onlyMembers { require(memberId[msg.sender] != 0); // member id must be in the mapping _; } function Steak() { owner = msg.sender; initialSale = 10000000 * 1000000000000000000; // 10M BOV units are awarded in the crowdsale. // Normally, the owner both starts and ends the crowdsale. // To guarantee that the crowdsale ends at some maximum point (at that tokens are distributed), // we calculate the absoluteEndBlock, the block beyond which anybody can end the crowdsale and distribute tokens. uint blocksPerHour = 212; uint maxCrowdsaleLifeFromLaunchDays = 40; // After about this many days from launch, anybody can end the crowdsale and distribute / claim their tokens. absoluteEndBlock = block.number + (blocksPerHour * 24 * maxCrowdsaleLifeFromLaunchDays); uint miningDays = 365; // Approximately how many days BOV can be mined from the launch of the contract. lastMiningBlock = block.number + (blocksPerHour * 24 * miningDays); dailyHashExpires = now; halvingInterval = 500; // How many steaks get awarded the given getSteakPrize() amount before the reward is halved. numberOfHalvings = 8; // How many times the steak prize gets halved before no more prize is awarded. // initialPrizeWeiValue = 50 finney; // 0.05 ether == 50 finney == 2.80 USD * 5 == 14 USD initialPrizeWeiValue = (357 finney / 10); // 0.0357 ether == 35.7 finney == 2.80 USD * 3.57 == 9.996 USD // To finish initializing, owner calls initMembers() and creditOwner() after launch. } // Add Madame BOV as a beef judge. function initMembers() onlyOwner { addMember(0, ''); // Must add an empty first member addMember(msg.sender, 'Madame BOV'); } // Send 1M BOV to Madame BOV. function creditOwner() onlyOwner { require(!ownerCredited); uint ownerAward = initialSale / 10; // 10% of the crowdsale amount. ownerCredited = true; // Can only be run once. mint(owner, ownerAward); } /* Add beef judge */ function addMember(address targetMember, bytes32 memberName) onlyOwner { uint id; if (memberId[targetMember] == 0) { memberId[targetMember] = members.length; id = members.length++; members[id] = Member({member: targetMember, memberSince: now, name: memberName}); } else { id = memberId[targetMember]; // Member m = members[id]; } MembershipChanged(targetMember, true); } function removeMember(address targetMember) onlyOwner { if (memberId[targetMember] == 0) revert(); memberId[targetMember] = 0; for (uint i = memberId[targetMember]; i<members.length-1; i++){ members[i] = members[i+1]; } delete members[members.length-1]; members.length--; } /* Submit a steak picture. (After crowdsale has ended.) * WARNING: Before taking the picture, call getDailyHash() and minutesToPost() * so you can be sure that you have the correct dailyHash and that it won't expire before you post it. */ function submitSteak(address addressToAward, bytes32 steakPicUrl) returns (uint submissionID) { require(crowdsaleHasEnded()); require(block.number <= lastMiningBlock); // Cannot submit beyond this block. submissionID = submissions.length++; // Increase length of array Submission storage s = submissions[submissionID]; s.recipient = addressToAward; s.url = steakPicUrl; s.judged = false; s.submissionApproved = false; s.todaysHash = getDailyHash(); // Each submission saves the hash code the user should take picture of in steak picture. PicAdded(msg.sender, submissionID, addressToAward, steakPicUrl); numSubmissions = submissionID+1; return submissionID; } // Retrieving any Submission must be done via this function, not `submissions()` function getSubmission(uint submissionID) public constant returns (address recipient, bytes32 url, bool judged, bool submissionApproved, address judgedBy, bytes32 adminComments, bytes32 todaysHash, uint awarded) { Submission storage s = submissions[submissionID]; recipient = s.recipient; url = s.url; // IMGUR url judged = s.judged; // Has an admin voted? submissionApproved = s.submissionApproved; // Has it been approved? judgedBy = s.judgedBy; // Admin who judged this steak adminComments = s.adminComments; // Admin should leave feedback on non-approved steaks todaysHash = s.todaysHash; // The hash in the image should match this hash. awarded = s.awarded; // Amount awarded // return (users[index].salaryId, users[index].name, users[index].userAddress, users[index].salary); // return (recipient, url, judged, submissionApproved, judgedBy, adminComments, todaysHash, awarded); } // Members judge steak pics, providing justification if necessary. function judge(uint submissionNumber, bool supportsSubmission, bytes32 justificationText) onlyMembers { Submission storage s = submissions[submissionNumber]; // Get the submission. require(!s.judged); // Musn't be judged. s.judged = true; s.judgedBy = msg.sender; s.submissionApproved = supportsSubmission; s.adminComments = justificationText; // Admin can add comments whether approved or not if (supportsSubmission) { // If it passed muster, credit the user and admin. uint prizeAmount = getSteakPrize(); // Calculate BOV prize s.awarded = prizeAmount; // Record amount in the Submission mint(s.recipient, prizeAmount); // Credit the user's account // Credit the member one-third of the prize amount. uint adminAward = prizeAmount.div(3); mint(msg.sender, adminAward); approvedSubmissions.push(s); } Judged(submissionNumber, supportsSubmission, msg.sender, justificationText); } // Calculate how many BOV are rewarded per approved steak pic. function getSteakPrize() public constant returns (uint) { require(initialPrizeBov > 0); // crowdsale must be over (endCrowdsale() calls setInitialPrize()) uint halvings = numberOfApprovedSteaks().div(halvingInterval); if (halvings > numberOfHalvings) { // After 8 halvings, no more BOV is awarded. return 0; } uint prize = initialPrizeBov; prize = prize >> halvings; // Halve the initial prize "halvings"-number of times. return prize; } function numberOfApprovedSteaks() public constant returns (uint) { return approvedSubmissions.length; } // Always call this before calling dailyHash and submitting a steak. // If expired, the new hash is set to the last block's hash. function getDailyHash() public returns (bytes32) { if (dailyHashExpires > now) { // If the hash hasn't expired yet, return it. return dailyHash; } else { // Udderwise, set the new dailyHash and dailyHashExpiration. // Get hash from the last block. bytes32 newHash = block.blockhash(block.number-1); dailyHash = newHash; // Set the new expiration, jumping ahead in 24-hour increments so the expiration time remains roughly constant from day to day (e.g. 3am). uint nextExpiration = dailyHashExpires + 24 hours; // It will already be expired, so set it to next possible date. while (nextExpiration < now) { // if it's still in the past, advance by 24 hours. nextExpiration += 24 hours; } dailyHashExpires = nextExpiration; return newHash; } } // Returns the amount of minutes to post with the current dailyHash function minutesToPost() public constant returns (uint) { if (dailyHashExpires > now) { return (dailyHashExpires - now) / 60; // returns minutes } else { return 0; } } function currentBlock() public constant returns (uint) { return block.number; } }
return true if the transaction can invest
function validInvestment() internal constant returns (bool) { bool withinPeriod = saleStarted && !saleEnded; bool nonZeroPurchase = (msg.value > 0); return withinPeriod && nonZeroPurchase; }
14,056,259
./full_match/1/0x75f719056873D7D66DAbD7C0869188a020dF4Bd3/sources/contracts/vesting/LinearVestingV2.sol
Get linear started status/
function isLinearStarted() public view virtual returns (bool) { return startLinearAt < block.timestamp; }
8,340,172