file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.4.23; import "./Verifier.sol"; contract WorglCoin { /***********************************/ /******* CONTRACT ATTRIBUTES *******/ /***********************************/ struct Consumer { bool isSet; address consumerAddress; uint tokenBalance; uint[] allOrders; } struct Business { bool isSet; address businessAddress; uint tokenBalance; uint[] itemsSupplied; bool complaintAgainst; uint noOfComplaints; uint[] allOrders; string name; } struct Order { uint orderID; uint itemID; address customerAddress; uint quantityOrdered; bool sent; uint delivery_location; } struct Item { uint itemID; string picture; string name; uint quantity; uint price; // in tokens address supplier; } address public master; uint public tokenValue; // measured in Wei uint public topUpLevel; mapping(address => Consumer) public consumerDetails; mapping(address => Business) public businessDetails; mapping(uint => Item) public allItems; mapping(uint => Order) public allOrders; address[] consumerAddresses; address[] businessAddresses; uint[] itemIDs; uint[] orderIDs; uint public noOfConsumers; uint public noOfBusinesses; uint public noOfItems; uint public noOfOrders; mapping(bytes32 => bool) eligibleConsumers; uint public balance; /***********************************/ /************* MODIFIERS ***********/ /***********************************/ modifier isOwner() { require(msg.sender == master); _; } modifier isConsumer() { require(consumerDetails[msg.sender].isSet); _; } modifier isBusiness() { require(businessDetails[msg.sender].isSet); _; } /***********************************/ /************** EVENTS *************/ /***********************************/ event ConsumerAdded(address consumerAddress); event BusinessAdded(address businessAddress); event ItemAdded(uint itemID); event OrderAdded(uint orderID, address businessAddress); event TokenDistribution(); event TopUp(); event ConsumerChange(address consumerAddress); event BusinessChange(address businessAddress); event ItemChange(uint itemID); event OrderChange(uint orderID, address businessAddress); /***********************************/ /********* PUBLIC FUNCTIONS ********/ /***********************************/ /* * @dev Constructor for WorglCoin * @param _tokenValue the value of each coin measured in Wei * @param _topUpLevel the number of tokens that each recipient will be topped up to */ constructor(uint _tokenValue, uint _topUpLevel) public { master = msg.sender; noOfConsumers = 0; noOfBusinesses = 0; noOfItems = 0; balance = 0; tokenValue = _tokenValue; topUpLevel = _topUpLevel; } /* * @dev allows the owner of the contract to change the address of the owner * @param newOwner the Ethereum address of the new owner */ function changeOwner(address newOwner) public isOwner { master = newOwner; } /* * @dev allows the owner of the contract to add an eligible consumer detail hash * @param hash SHA-256 hash of the details of an eligible citizen */ function addConsumerHash(bytes32 hash) public isOwner { require(!eligibleConsumers[hash]); eligibleConsumers[hash] = true; } /* * @dev allows the owner of the contract to add a token recipient * @param hash SHA-256 hash of the consumer signing up * @param a 'a' paramater of the zero-knowledge proof * @param a_p 'a_p' paramater of the zero-knowledge proof * @param b 'b' paramater of the zero-knowledge proof * @param b_p 'b_p' paramater of the zero-knowledge proof * @param c 'c' paramater of the zero-knowledge proof * @param c_p 'c_p' paramater of the zero-knowledge proof * @param h 'h' paramater of the zero-knowledge proof * @param k 'k' paramater of the zero-knowledge proof * @param input public input paramaters of the zero-knowledge proof */ function consumerSignUp( bytes32 hash, uint[2] a, uint[2] a_p, uint[2][2] b, uint[2] b_p, uint[2] c, uint[2] c_p, uint[2] h, uint[2] k, uint[33] input) public { // Check that the address is not already in the system require(!consumerDetails[msg.sender].isSet); require(eligibleConsumers[hash]); require(check32BitsHash(input, hash)); require(Verifier.verifyTx(a, a_p, b, b_p, c, c_p, h, k, input)); // Add the consumer to the database Consumer memory newConsumer; newConsumer.isSet = true; newConsumer.consumerAddress = msg.sender; newConsumer.tokenBalance = 0; consumerDetails[msg.sender] = newConsumer; // Increment the number of consumers and trigger the event noOfConsumers = add(noOfConsumers, 1); consumerAddresses.push(msg.sender); emit ConsumerAdded(msg.sender); } /* * @dev allows the owner of the contract to add a business * @param _consumerAddress the Ethereum address of the business to be added * @param _name the name of the business to be added */ function addBusiness(address _businessAddress, string _name) public isOwner { // Check that the address is not already in the system require(!businessDetails[_businessAddress].isSet); // Add the business to the database Business memory newBusiness; newBusiness.isSet = true; newBusiness.businessAddress = _businessAddress; newBusiness.tokenBalance = 0; newBusiness.complaintAgainst = false; newBusiness.noOfComplaints = 0; newBusiness.name = _name; businessDetails[_businessAddress] = newBusiness; // Increment the number of businesses and trigger the event noOfBusinesses = add(noOfBusinesses, 1); businessAddresses.push(_businessAddress); emit BusinessAdded(_businessAddress); } /* * @dev allows the owner of the contract to change the top up balance * @param newTopUpLevel the new top up balance */ function changeTokenBalance(uint newTopUpLevel) public isOwner { topUpLevel = newTopUpLevel; emit TopUp(); } /* * @dev allows the owner of the contract to change the value of the tokens * @param newValue the new value that the tokens can be exchanged for in Wei */ function changeTokenValue(uint newValue) public isOwner { tokenValue = newValue; emit TopUp(); } /* * @dev allows the owner of the contract to reset all token balances for consumers */ function resetTokenBalance() public isOwner payable { // Reset all consumer balances for(uint i = 0; i<noOfConsumers; i++) { consumerDetails[consumerAddresses[i]].tokenBalance = topUpLevel; } // Pay out all funds to business for (uint j = 0; j<noOfBusinesses; j++) { uint tokenBalance = businessDetails[businessAddresses[j]].tokenBalance; businessDetails[businessAddresses[j]].tokenBalance = 0; balance = sub(balance, tokenBalance * tokenValue); businessAddresses[j].transfer(tokenBalance * tokenValue); } emit TokenDistribution(); } /* * @dev allows anyone to view the token balance of another consumer * @param address the new value that the tokens can be exchanged for in Wei * @return balances the balance of the address */ function getTokenBalance(address holderAddress) public view returns (string, uint) { if(consumerDetails[holderAddress].isSet){ return ('Consumer', consumerDetails[holderAddress].tokenBalance); } else if(businessDetails[holderAddress].isSet){ return ('Business', businessDetails[holderAddress].tokenBalance); } else if(holderAddress == master){ return ('Contract Owner', 0); } else { return ('Not Signed Up', 0); } } /* * @dev allows a business to list an item for sale * @param _name the name of the item for sale * @param _quantity the quantity of the item for sale * @param _price the number of tokens required to buy the item */ function sellItem(string _name, string _picture, uint _quantity, uint _price) public isBusiness { // Have to ensure the business has no complaints against it to list items require(!businessDetails[msg.sender].complaintAgainst); // Add the item to the database uint itemIDNumber = noOfItems; Item memory newItem; newItem.itemID = itemIDNumber; newItem.name = _name; newItem.picture = _picture; newItem.quantity = _quantity; newItem.price = _price; newItem.supplier = msg.sender; allItems[itemIDNumber] = newItem; // Increment the number of items and trigger the event businessDetails[msg.sender].itemsSupplied.push(itemIDNumber); itemIDs.push(itemIDNumber); noOfItems = add(noOfItems, 1); emit ItemAdded(itemIDNumber); } /* * @dev allows a consumer to submit an order for an item * @param _itemID the ID of the item wishing to be bought * @return _quantity the quantity of the item wanting to be bought */ function buyItem(uint _itemID, uint _quantity, uint _delivery_location) public isConsumer { uint totalCost = allItems[_itemID].price * _quantity; require(consumerDetails[msg.sender].tokenBalance >= totalCost); uint _orderID = noOfOrders; // Add the order to the database Order memory newOrder; newOrder.orderID = _orderID; newOrder.itemID = _itemID; newOrder.customerAddress = msg.sender; newOrder.quantityOrdered = _quantity; newOrder.sent = false; newOrder.delivery_location = _delivery_location; allOrders[_orderID] = newOrder; // Increment the number of orders and trigger the event noOfOrders = add(noOfOrders, 1); orderIDs.push(_orderID); businessDetails[allItems[_itemID].supplier].allOrders.push(_orderID); // Add to consumers orders consumerDetails[msg.sender].allOrders.push(_orderID); // Decrement the tokens from the consumers balance consumerDetails[msg.sender].tokenBalance = sub(consumerDetails[msg.sender].tokenBalance, totalCost); // Decrement the quantity from the total quantity of items available allItems[_itemID].quantity = sub(allItems[_itemID].quantity, _quantity); emit OrderAdded(_orderID, allItems[_itemID].supplier); emit ItemChange(_itemID); } /* * @dev allows a business to mark an order as sent * @param _orderID the ID of the order being mark as sent */ function markOrderAsSent(uint _orderID) public isBusiness { // Make sure it is the actual supplier marking an order as sent require(allItems[allOrders[_orderID].itemID].supplier == msg.sender); allOrders[_orderID].sent = true; // Transfer tokens to the business uint totalRevenue = allItems[allOrders[_orderID].itemID].price * allOrders[_orderID].quantityOrdered; businessDetails[msg.sender].tokenBalance = add(businessDetails[msg.sender].tokenBalance, totalRevenue); emit OrderChange(_orderID, msg.sender); } /* * @dev allows a customer to complain about a business if they haven't received item * @param _orderID the ID of the order that is being complained about */ function makeComplaint(uint _orderID) public isConsumer { require(allOrders[_orderID].customerAddress == msg.sender); require(allOrders[_orderID].sent); businessDetails[allItems[allOrders[_orderID].itemID].supplier].complaintAgainst = true; businessDetails[allItems[allOrders[_orderID].itemID].supplier].noOfComplaints = add(businessDetails[allItems[allOrders[_orderID].itemID].supplier].noOfComplaints,1); emit OrderChange(_orderID, allItems[allOrders[_orderID].itemID].supplier); } /* * @dev allows the owner of the contract to reset a business complaint * @param _businessAddress the address of the business */ function resetComplaint(uint _orderID) public { require(msg.sender == allOrders[_orderID].customerAddress); businessDetails[allItems[allOrders[_orderID].itemID].supplier].noOfComplaints = sub(businessDetails[allItems[allOrders[_orderID].itemID].supplier].noOfComplaints, 1); if (businessDetails[allItems[allOrders[_orderID].itemID].supplier].noOfComplaints == 0) { businessDetails[allItems[allOrders[_orderID].itemID].supplier].complaintAgainst = false; } emit OrderChange(_orderID, allItems[allOrders[_orderID].itemID].supplier); } /* * @dev allows you to return all consumer addresses */ function getAllConsumers() public view returns(address[]) { return consumerAddresses; } /* * @dev allows you to return all business addresses */ function getAllBusinesses() public view returns(address[]) { return businessAddresses; } /* * @dev allows you to return all order IDs for a consumer or business * @param _consumerAddress the address of the consumer or business */ function getAllOrders(address holderAddress) public view returns(uint[]) { if(consumerDetails[holderAddress].isSet){ return consumerDetails[holderAddress].allOrders; } else if(businessDetails[holderAddress].isSet){ return businessDetails[holderAddress].allOrders; } else { return; } } /* * @dev allows you to return all items */ function getAllItems() public view returns(uint[]) { return itemIDs; } /* * @dev allows you to return all order details * @param _orderID the ID of the order */ function getOrderDetails(uint _orderID) public view returns(uint, address, uint, bool, uint) { return ( allOrders[_orderID].itemID, allOrders[_orderID].customerAddress, allOrders[_orderID].quantityOrdered, allOrders[_orderID].sent, allOrders[_orderID].delivery_location); } /* * @dev allows you to return all item details * @param _itemID the ID of the item */ function getItemDetails(uint _itemID) public view returns(string, string, uint, uint, address) { return ( allItems[_itemID].name, allItems[_itemID].picture, allItems[_itemID].quantity, allItems[_itemID].price, allItems[_itemID].supplier); } /* * @dev allows you to return all item details * @param _businessAddress the addres of the business */ function getBusinessDetails(address _businessAddress) public view returns(uint, uint[], bool, uint, uint[], string) { return ( businessDetails[_businessAddress].tokenBalance, businessDetails[_businessAddress].itemsSupplied, businessDetails[_businessAddress].complaintAgainst, businessDetails[_businessAddress].noOfComplaints, businessDetails[_businessAddress].allOrders, businessDetails[_businessAddress].name); } // `fallback` function called when eth is sent to Payable contract function topUpContract() public payable isOwner { balance = add(balance, msg.value); emit TopUp(); } /***********************************/ /******** INTERNAL FUNCTIONS *******/ /***********************************/ /* * @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; } /* * @dev Checks an array of bits matches a hex * @param input_bits the first 32 bits of the hash to be checked * @param hash_value the full hash * @return bool whether the */ function check32BitsHash(uint[33] input_bits, bytes32 hash_value) internal pure returns (bool) { uint hash_value_check1; uint hash_value_check2; uint input_bits_check1; uint input_bits_check2; bytes1 current_bytes1_hash; for (uint i=0; i<4; i++) { current_bytes1_hash = hash_value[0]; // First check the left value hash_value_check1 = getLeftCoordinate(hash_value[i]); input_bits_check1 = (input_bits[(i*2*4)] * 8) + (input_bits[(i*2*4)+1] * 4) + (input_bits[(i*2*4)+2] * 2) + (input_bits[(i*2*4)+3] * 1); if (hash_value_check1 != input_bits_check1) { return false; } hash_value_check2 = getRightCoordinate(hash_value[i]); input_bits_check2 = (input_bits[(i*2*4)+4] * 8) + (input_bits[(i*2*4)+5] * 4) + (input_bits[(i*2*4)+6] * 2) + (input_bits[(i*2*4)+7] * 1); if (hash_value_check2 != input_bits_check2) { return false; } } return true; } /* * @dev Gets the left most 4 bits of a byte1 * @param input_bits the 8 bit input * @return bool returns an integer representation of the hex value */ function getRightCoordinate(byte input) internal pure returns (uint) { byte val = input & byte(15); return uint(val); } /* * @dev Gets the right most 4 bits of a byte1 * @param input_bits the 8 bit input * @return bool returns an integer representation of the hex value */ function getLeftCoordinate(byte input) internal pure returns (uint) { byte val = input >> 4; return uint(val); } }
allows a customer to complain about a business if they haven't received item _orderID the ID of the order that is being complained about/
function makeComplaint(uint _orderID) public isConsumer { require(allOrders[_orderID].customerAddress == msg.sender); require(allOrders[_orderID].sent); businessDetails[allItems[allOrders[_orderID].itemID].supplier].complaintAgainst = true; businessDetails[allItems[allOrders[_orderID].itemID].supplier].noOfComplaints = add(businessDetails[allItems[allOrders[_orderID].itemID].supplier].noOfComplaints,1); emit OrderChange(_orderID, allItems[allOrders[_orderID].itemID].supplier); }
2,538,341
./full_match/56/0x094244e8d6782226abeD76E0f4C60f30e9CCB2B3/sources/RevenueSharingPoolFactory.sol
Round off random timestamp to week _timestamp The timestamp to be rounded off
function _timestampToFloorWeek(uint256 _timestamp) internal pure returns (uint256) { return (_timestamp / WEEK) * WEEK; }
3,236,373
/** *Submitted for verification at Etherscan.io on 2022-02-22 */ // Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File contracts/ERC721Opt.sol pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintToDeadAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error TransferToDeadAddress(); error UnableGetTokenOwnerByIndex(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3..). */ contract ERC721Opt is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; uint256 internal _nextTokenId = 1; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owners details // An empty struct value does not necessarily mean the token is unowned. See ownerOf implementation for details. mapping(uint256 => address) internal _owners; // Mapping owner address to balances 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; // Address to use for burned accounting address constant DEAD_ADDR = 0x000000000000000000000000000000000000dEaD; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { // Counter underflow is impossible as burned cannot be incremented // more than _nextTokenId - 1 times unchecked { return (_nextTokenId - 1) - balanceOf(DEAD_ADDR); } } /** * @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) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); unchecked { for (uint256 curr = tokenId;; curr--) { owner = _owners[curr]; if (owner != address(0)) { 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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 = ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ApprovalCallerNotOwnerNorApproved(); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert TransferToNonERC721ReceiverImplementer(); } function _isApprovedOrOwner(address sender, uint256 tokenId) internal view virtual returns (bool) { address owner = ownerOf(tokenId); return (sender == owner || getApproved(tokenId) == sender || isApprovedForAll(owner, sender)); } /** * @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`), */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId > 0 && tokenId < _nextTokenId && _owners[tokenId] != DEAD_ADDR; } function _mint(address to, uint256 quantity) internal virtual { _mint(to, quantity, '', false); } function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal virtual { uint256 startTokenId = _nextTokenId; if (to == address(0)) revert MintToZeroAddress(); if (to == DEAD_ADDR) revert MintToDeadAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance overflow if current value + quantity > 1.56e77 (2**256) - 1 // updatedIndex overflows if _nextTokenId + quantity > 1.56e77 (2**256) - 1 unchecked { _balances[to] += quantity; _owners[startTokenId] = to; uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { if (!_checkOnERC721Received(address(0), to, updatedIndex, _data)) revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _nextTokenId = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { address owner = ownerOf(tokenId); bool isApprovedOrOwner = (_msgSender() == owner || isApprovedForAll(owner, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (owner != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); if (to == DEAD_ADDR) revert TransferToDeadAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, owner); // Underflow of the sender's balance is impossible because we check for // owner above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; // If the owner slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_owners[nextTokenId] == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _nextTokenId) { _owners[nextTokenId] = owner; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, 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 = ownerOf(tokenId); _beforeTokenTransfers(owner, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, owner); // Underflow of the sender's balance is impossible because we check for // owner above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _balances[owner] -= 1; _balances[DEAD_ADDR] += 1; _owners[tokenId] = DEAD_ADDR; // If the owner slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_owners[nextTokenId] == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _nextTokenId) { _owners[nextTokenId] = owner; } } } emit Transfer(owner, address(0), tokenId); _afterTokenTransfers(owner, address(0), tokenId, 1); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) revert TransferToNonERC721ReceiverImplementer(); else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File contracts/extensions/ERC721OptOwnersExplicit.sol pragma solidity ^0.8.4; error AllOwnersHaveBeenSet(); error QuantityMustBeNonZero(); error NoTokensMintedYet(); abstract contract ERC721OptOwnersExplicit is ERC721Opt { uint256 public nextOwnerToExplicitlySet = 1; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { if (quantity == 0) revert QuantityMustBeNonZero(); if (_nextTokenId == 1) revert NoTokensMintedYet(); uint256 _nextOwnerToExplicitlySet = nextOwnerToExplicitlySet; if (_nextOwnerToExplicitlySet >= _nextTokenId) revert AllOwnersHaveBeenSet(); // Index underflow is impossible. // Counter or index overflow is incredibly unrealistic. unchecked { uint256 endIndex = _nextOwnerToExplicitlySet + quantity - 1; // Set the end index to be the last token index if (endIndex + 1 > _nextTokenId) { endIndex = _nextTokenId - 1; } for (uint256 i = _nextOwnerToExplicitlySet; i <= endIndex; i++) { if (_owners[i] == address(0) && _owners[i] != DEAD_ADDR) { address ownership = ownerOf(i); _owners[i] = ownership; } } nextOwnerToExplicitlySet = endIndex + 1; } } } // File contracts/extensions/ERC721OptBurnable.sol pragma solidity ^0.8.4; error BurnCallerNotOwnerNorApproved(); /** * @title ERC721Opt Burnable Token * @dev ERC721Opt Token that can be irreversibly burned (destroyed). */ abstract contract ERC721OptBurnable is ERC721Opt { /** * @dev Burns `tokenId`. See {ERC721Opt-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert BurnCallerNotOwnerNorApproved(); _burn(tokenId); } } // File contracts/extensions/ERC721OptBatchBurnable.sol pragma solidity ^0.8.4; /** * @title ERC721Opt Batch Burnable Token * @dev ERC721Opt Token that can be irreversibly batch burned (destroyed). */ abstract contract ERC721OptBatchBurnable is ERC721OptBurnable { /** * @dev Perform burn on a batch of tokens */ function batchBurn(uint16[] memory tokenIds) public virtual { for (uint16 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert BurnCallerNotOwnerNorApproved(); _burn(tokenIds[i]); } } } // File contracts/extensions/ERC721OptBatchTransferable.sol pragma solidity ^0.8.4; /** * @title ERC721Opt Batch Transferable Token * @dev ERC721Opt Token that can be batch transfered */ abstract contract ERC721OptBatchTransferable is ERC721Opt { /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint16[] tokenIds ); /** * @dev Perform transferFrom on a batch of tokens */ function batchTransferFrom( address from, address to, uint16[] memory tokenIds ) public virtual { for (uint16 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert TransferCallerNotOwnerNorApproved(); transferFrom(from, to, tokenIds[i]); } emit TransferBatch(_msgSender(), from, to, tokenIds); } /** * @dev Perform safeTransferFrom on a batch of tokens */ function safeBatchTransferFrom( address from, address to, uint16[] memory tokenIds ) public virtual { safeBatchTransferFrom(from, to, tokenIds, ''); } /** * @dev Perform safeTransferFrom on a batch of tokens */ function safeBatchTransferFrom( address from, address to, uint16[] memory tokenIds, bytes memory _data ) public virtual { for (uint256 i = 0; i < tokenIds.length; ++i) { if (!_isApprovedOrOwner(_msgSender(), tokenIds[i])) revert TransferCallerNotOwnerNorApproved(); safeTransferFrom(from, to, tokenIds[i], _data); } emit TransferBatch(_msgSender(), from, to, tokenIds); } } // File contracts/DAOBnBNFT.sol pragma solidity ^0.8.4; contract OpenSeaOwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OpenSeaOwnableDelegateProxy) public proxies; } interface IToken { /** * @dev Called from DAOBnBNFT when one is transfered/minted/burned */ function updateRewards(address _user) external; } error CardTypeQueryForNonexistentToken(); error OnlyMintersCanMint(); error NoMintAmountProvided(); error AllSilverCardsMinted(); error AllBlackCardsMinted(); contract DAOBnBNFT is Ownable, ERC721Opt, ERC721OptOwnersExplicit, ERC721OptBatchBurnable, ERC721OptBatchTransferable { using Strings for uint16; /* Base URI for token URIs */ string public baseURI; /* OpenSea user account proxy */ address public openSeaProxyRegistryAddress; /* Token contract */ IToken public token; uint16 silverCardsMax = 6400; uint16 blackCardsMax = 2700; uint16 blackCardsMinted; /* mapping of each wallets black cards */ mapping(address => uint16) public walletBlackCards; /* Minter addressess */ mapping(address => bool) public minters; /* mapping of each token id to card type 0 = silver, 1 = black */ mapping(uint16 => bool) _blackCardTokenIds; constructor(string memory name_, string memory symbol_, string memory _initialBaseURI, address _openSeaProxyRegistryAddress, address[] memory _minters) ERC721Opt(name_, symbol_) { baseURI = _initialBaseURI; openSeaProxyRegistryAddress = _openSeaProxyRegistryAddress; for (uint256 i = 0; i < _minters.length; i++) { minters[_minters[i]] = true; } } /** * @dev Get silver cards left for sale */ function silverCardsLeft() public view returns (uint256) { return silverCardsMax - (_nextTokenId - 1 - blackCardsMinted); } /** * @dev Get black cards left for sale */ function blackCardsLeft() public view returns (uint256) { return blackCardsMax - blackCardsMinted; } /** * @dev Get the card type for a specific tokenId */ function tokenCardType(uint16 tokenId) public view returns (string memory) { if (!_exists(tokenId)) revert CardTypeQueryForNonexistentToken(); if (_blackCardTokenIds[tokenId]) { return "black"; } return "silver"; } /** * @dev Override to if default approved for OS proxy accounts or normal approval */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. OpenSeaProxyRegistry openSeaProxyRegistry = OpenSeaProxyRegistry( openSeaProxyRegistryAddress ); if (address(openSeaProxyRegistry.proxies(owner)) == operator) { return true; } return ERC721Opt.isApprovedForAll(owner, operator); } /** * @dev Override to change the baseURI used in tokenURI */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev Override to change tokenURI format */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(_baseURI(), tokenCardType(uint16(tokenId)), '.json')) : ''; } /** * @dev Mint of specific card type to address. */ function mint(uint16 silverCardsAmount, uint16 blackCardsAmount, address to) public { if(!minters[msg.sender]) revert OnlyMintersCanMint(); if(silverCardsAmount + blackCardsAmount == 0) revert NoMintAmountProvided(); if(_nextTokenId - 1 - blackCardsMinted + silverCardsAmount > silverCardsMax) revert AllSilverCardsMinted(); if(blackCardsMinted + blackCardsAmount > blackCardsMax) revert AllBlackCardsMinted(); if (blackCardsAmount > 0) { blackCardsMinted += blackCardsAmount; uint16 tokenId = uint16(_nextTokenId) + silverCardsAmount; for (uint16 i; i < blackCardsAmount; i++) { _blackCardTokenIds[tokenId++] = true; } } _safeMint(to, silverCardsAmount + blackCardsAmount, ''); } /** * @dev Override so we can update token rewards before transfer happens */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override { if (address(token) != address(0)) { token.updateRewards(from); token.updateRewards(to); } uint16 blackCards; for(uint16 i = uint16(startTokenId); i < startTokenId + quantity; i++) { if (_blackCardTokenIds[i]) { blackCards += 1; } } if (from != address(0)) { walletBlackCards[from] -= blackCards; } if (to != address(0)) { walletBlackCards[to] += blackCards; } super._beforeTokenTransfers(from, to, startTokenId, quantity); } /** * @dev Set the base uri for token metadata */ function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } /** * @dev Set minter status for addresses */ function setMinters(address[] calldata addresses, bool allowed) external onlyOwner { for(uint256 i = 0; i < addresses.length; i++) { minters[addresses[i]] = allowed; } } /** * @dev Update available cards */ function updateAvailableCards(uint16 silverCards, uint16 blackCards) external onlyOwner { silverCardsMax = silverCards; blackCardsMax = blackCards; } /** * @dev Set the token contract */ function setToken(IToken _token) external onlyOwner { token = _token; } /** * @dev Force update all owners for better transfers */ function updateOwners(uint256 quantity) external onlyOwner { _setOwnersExplicit(quantity); } } // File @openzeppelin/contracts/utils/cryptography/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed 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)); } } // File contracts/DAOBnBMinter.sol pragma solidity ^0.8.0; contract DAOBnBMinter is Ownable { using Strings for uint16; using ECDSA for bytes32; /* DAObnb NFT contract */ DAOBnBNFT nftContract; /* Is Pre Sale Active */ bool public preSaleIsActive; /* Is Sale Active */ bool public saleIsActive; /* If > 0 limit pre sale silver cards purchases per address */ uint16 public maxPreSaleSilverCardsPerAddress = 2; /* If > 0 limit pre sale black cards purchases per address */ uint16 public maxPreSaleBlackCardsPerAddress = 1; /* Limit how many silver cards can be purchased in single transaction for pre sale */ uint16 public maxPreSaleSilverCardsPerTransaction = 2; /* Limit how many black cards can be purchased in single transaction for pre sale */ uint16 public maxPreSaleBlackCardsPerTransaction = 1; /* Limit how many silver cards can be purchased in single transaction for public sale */ uint16 public maxSilverCardsPerTransaction = 16; /* Limit how many black cards can be purchased in single transaction for public sale */ uint16 public maxBlackCardsPerTransaction = 4; /* silver cards reserved for marketing */ uint16 public reservedSilverCards = 640; /* black cards reserved for marketing */ uint16 public reservedBlackCards = 270; /* Price for silver card during pre sale */ uint256 public preSaleSilverCardPrice = 0.175 ether; /* Price for black card during pre sale */ uint256 public preSaleBlackCardPrice = 0.7 ether; /* Price for silver card during public sale */ uint256 public silverCardPrice = 0.175 ether; /* Price for black card during public sale */ uint256 public blackCardPrice = 0.7 ether; /* PreSaleList Signature Addresses */ mapping(address => bool) public preSaleListSignatureAddresses; /* PreSaleList Signature Nounces used */ mapping(uint16 => address) public preSaleListSignatureUsedNounces; /* PreSaleListed addressess */ mapping(address => bool) public preSaleListedAddresses; /* Silver cards minted per address during pre sale */ mapping(address => uint16) public preSaleSilverCardPurchases; /* Black cards minted per address during pre sale */ mapping(address => uint16) public preSaleBlackCardPurchases; constructor( DAOBnBNFT _nftContract, address[] memory _preSaleListSignatureAddresses ) { nftContract = _nftContract; for (uint256 i = 0; i < _preSaleListSignatureAddresses.length; i++) { preSaleListSignatureAddresses[_preSaleListSignatureAddresses[i]] = true; } } function getPreSaleListMessage(uint16 nounce, address sender) public pure returns (bytes32) { if (nounce > 0) { return keccak256(abi.encodePacked('ProjectId: 621285d3e200cdf5b5ef5704, Nounce: ', nounce)); } return keccak256(abi.encodePacked('ProjectId: 621285d3e200cdf5b5ef5704, Address: ', sender)); } function mintPreSale(uint16 silverCardsAmount, uint16 blackCardsAmount, uint16 nounce, bytes calldata signature) external payable { require(preSaleIsActive, 'Pre sale must be active to mint pre sale'); require(!saleIsActive, 'Regular sale is already active'); require( silverCardsAmount + blackCardsAmount > 0, 'No amounts provided' ); require( silverCardsAmount <= maxPreSaleSilverCardsPerTransaction, 'Can not mint that many silver tokens in a single transaction during the pre sale' ); require( blackCardsAmount <= maxPreSaleBlackCardsPerTransaction, 'Can not mint that many black tokens in a single transaction during the pre sale' ); require( silverCardsAmount <= nftContract.silverCardsLeft() - reservedSilverCards, 'Sold Out' ); require( blackCardsAmount <= nftContract.blackCardsLeft() - reservedBlackCards, 'Sold Out' ); require( preSaleSilverCardPurchases[msg.sender] + silverCardsAmount <= maxPreSaleSilverCardsPerAddress, 'Can only mint so many silver cards during the presale' ); require( preSaleBlackCardPurchases[msg.sender] + blackCardsAmount <= maxPreSaleBlackCardsPerAddress, 'Can only mint so many black cards during the presale' ); require( msg.value >= (preSaleSilverCardPrice * silverCardsAmount) + (preSaleBlackCardPrice * blackCardsAmount), 'Ether value sent is not correct' ); require(preSaleListedAddresses[_msgSender()] || signature.length > 0, 'Signature required for pre sale'); require(nounce == 0 || preSaleListSignatureUsedNounces[nounce] == address(0) || preSaleListSignatureUsedNounces[nounce] == _msgSender(), 'Invalid or used nounce'); if (!preSaleListedAddresses[_msgSender()] && preSaleListSignatureUsedNounces[nounce] != _msgSender()) { bytes32 message = getPreSaleListMessage(nounce, _msgSender()); bytes32 messageHash = message.toEthSignedMessageHash(); address signer = messageHash.recover(signature); require(preSaleListSignatureAddresses[signer], 'Signature invalid'); if (nounce > 0) { preSaleListSignatureUsedNounces[nounce] = _msgSender(); } } preSaleSilverCardPurchases[msg.sender] += silverCardsAmount; preSaleBlackCardPurchases[msg.sender] += blackCardsAmount; nftContract.mint(silverCardsAmount, blackCardsAmount, msg.sender); } function mint(uint16 silverCardsAmount, uint16 blackCardsAmount) external payable { require(saleIsActive, 'Regular sale is not active'); require( silverCardsAmount + blackCardsAmount > 0, 'No amounts provided' ); require( silverCardsAmount <= maxSilverCardsPerTransaction, 'Can not mint that many silver cards in a single transaction during the sale' ); require( blackCardsAmount <= maxBlackCardsPerTransaction, 'Can not mint that many black cards in a single transaction during the sale' ); require( silverCardsAmount <= nftContract.silverCardsLeft() - reservedSilverCards, 'Sold Out' ); require( blackCardsAmount <= nftContract.blackCardsLeft() - reservedBlackCards, 'Sold Out' ); require( msg.value >= (silverCardPrice * silverCardsAmount) + (blackCardPrice * blackCardsAmount), 'Ether value sent is not correct' ); nftContract.mint(silverCardsAmount, blackCardsAmount, _msgSender()); } /** * @dev Update a list of addresses to be allowed to be used for signature based preSaleList */ function updatePreSaleListSignatureAddresses(address[] memory _preSaleListSignatureAddresses, bool allowed) external onlyOwner { for (uint256 i = 0; i < _preSaleListSignatureAddresses.length; i++) { preSaleListSignatureAddresses[_preSaleListSignatureAddresses[i]] = allowed; } } /** * @dev Update a list of addresses to be allowed in preSaleList */ function updatePreSaleListedAddresses(address[] memory _preSaleListedAddresses, bool allowed) external onlyOwner { for (uint256 i = 0; i < _preSaleListedAddresses.length; i++) { preSaleListedAddresses[_preSaleListedAddresses[i]] = allowed; } } function flipPreSaleState() external onlyOwner { preSaleIsActive = !preSaleIsActive; } function flipSaleState() external onlyOwner { saleIsActive = !saleIsActive; } function setMaxPreSaleCardsPerAddress(uint16 _silverCardsAmount, uint16 _blackCardsAmount) external onlyOwner { maxPreSaleSilverCardsPerAddress = _silverCardsAmount; maxPreSaleBlackCardsPerAddress = _blackCardsAmount; } function setMaxPreSaleCardsPerTransaction(uint16 _silverCardsAmount, uint16 _blackCardsAmount) external onlyOwner { maxPreSaleSilverCardsPerTransaction = _silverCardsAmount; maxPreSaleBlackCardsPerTransaction = _blackCardsAmount; } function setMaxCardsPerTransaction(uint16 _silverCardsAmount, uint16 _blackCardsAmount, bool updatePreSaleAlso) external onlyOwner { maxSilverCardsPerTransaction = _silverCardsAmount; maxBlackCardsPerTransaction = _blackCardsAmount; if (updatePreSaleAlso) { maxPreSaleSilverCardsPerTransaction = _silverCardsAmount; maxPreSaleBlackCardsPerTransaction = _blackCardsAmount; } } function setReservedCards(uint16 _silverCardsAmount, uint16 _blackCardsAmount) external onlyOwner { reservedSilverCards = _silverCardsAmount; reservedBlackCards = _blackCardsAmount; } function setPreSalePrice(uint256 _silverCardPrice, uint256 _blackCardPrice) external onlyOwner { preSaleSilverCardPrice = _silverCardPrice; preSaleBlackCardPrice = _blackCardPrice; } function setPrice(uint256 _silverCardPrice, uint256 _blackCardPrice, bool updatePreSaleAlso) external onlyOwner { silverCardPrice = _silverCardPrice; blackCardPrice = _blackCardPrice; if (updatePreSaleAlso) { preSaleSilverCardPrice = _silverCardPrice; preSaleBlackCardPrice = _blackCardPrice; } } function reserveMint(uint16 silverCardsAmount, uint16 blackCardsAmount, address[] calldata to) external onlyOwner { require( (silverCardsAmount * to.length) <= reservedSilverCards, 'Not enough reserve left for team' ); require( (blackCardsAmount * to.length) <= reservedBlackCards, 'Not enough reserve left for team' ); require( silverCardsAmount + blackCardsAmount > 0, 'No amounts provided' ); for (uint16 i = 0; i < to.length; i++) { nftContract.mint(silverCardsAmount, blackCardsAmount, to[i]); } reservedSilverCards = uint16(reservedSilverCards - (silverCardsAmount * to.length)); reservedBlackCards = uint16(reservedBlackCards - (blackCardsAmount * to.length)); } function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } }
Set minter status for addresses/
function setMinters(address[] calldata addresses, bool allowed) external onlyOwner { for(uint256 i = 0; i < addresses.length; i++) { minters[addresses[i]] = allowed; } }
7,850,423
/** *Submitted for verification at Etherscan.io on 2021-02-15 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.6.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // File: contracts/library/AddressArrayUtils.sol pragma solidity ^0.6.12; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } } // File: contracts/interfaces/ILimaSwap.sol pragma solidity ^0.6.12; interface ILimaSwap { function getGovernanceToken(address token) external view returns (address); function getExpectedReturn( address fromToken, address toToken, uint256 amount ) external view returns (uint256 returnAmount); function swap( address recipient, address from, address to, uint256 amount, uint256 minReturnAmount ) external returns (uint256 returnAmount); function unwrap( address interestBearingToken, uint256 amount, address recipient ) external; function getUnderlyingAmount(address token, uint256 amount) external returns (uint256 underlyingAmount); } // File: contracts/interfaces/ILimaTokenStorage.sol pragma solidity ^0.6.12; /** * @title LimaToken * @author Lima Protocol * * Standard LimaToken. */ interface ILimaTokenStorage { function MAX_UINT256() external view returns (uint256); function WETH() external view returns (address); function LINK() external view returns (address); function currentUnderlyingToken() external view returns (address); // address external owner; function limaSwap() external view returns (ILimaSwap); function rebalanceBonus() external view returns (uint256); function rebalanceGas() external view returns (uint256); //Fees function feeWallet() external view returns (address); function burnFee() external view returns (uint256); function mintFee() external view returns (uint256); function performanceFee() external view returns (uint256); function requestId() external view returns (bytes32); //Rebalance function lastUnderlyingBalancePer1000() external view returns (uint256); function lastRebalance() external view returns (uint256); function rebalanceInterval() external view returns (uint256); function limaGovernance() external view returns (address); function owner() external view returns (address); function governanceToken(uint256 _protocoll) external view returns (address); /* ============ Setter ============ */ function addUnderlyingToken(address _underlyingToken) external; function removeUnderlyingToken(address _underlyingToken) external; function setCurrentUnderlyingToken(address _currentUnderlyingToken) external; function setFeeWallet(address _feeWallet) external; function setBurnFee(uint256 _burnFee) external; function setMintFee(uint256 _mintFee) external; function setLimaToken(address _limaToken) external; function setPerformanceFee(uint256 _performanceFee) external; function setLastUnderlyingBalancePer1000( uint256 _lastUnderlyingBalancePer1000 ) external; function setLastRebalance(uint256 _lastRebalance) external; function setLimaSwap(address _limaSwap) external; function setRebalanceInterval(uint256 _rebalanceInterval) external; /* ============ View ============ */ function isUnderlyingTokens(address _underlyingToken) external view returns (bool); } // File: contracts/interfaces/IInvestmentToken.sol pragma solidity ^0.6.12; interface IInvestmentToken { function isInvestmentToken(address _investmentToken) external view returns (bool); function removeInvestmentToken(address _investmentToken) external; function addInvestmentToken(address _investmentToken) external; } // File: contracts/interfaces/IAmunUser.sol pragma solidity ^0.6.12; interface IAmunUser { function isAmunUser(address _amunUser) external view returns (bool); function isOnlyAmunUserActive() external view returns (bool); } // File: contracts/interfaces/ILimaTokenHelper.sol pragma solidity ^0.6.12; /** * @title ILimaTokenHelper * @author Lima Protocol * * Standard ILimaTokenHelper. */ interface ILimaTokenHelper is IInvestmentToken, IAmunUser, ILimaTokenStorage { function getNetTokenValue(address _targetToken) external view returns (uint256 netTokenValue); function getNetTokenValueOf(address _targetToken, uint256 _amount) external view returns (uint256 netTokenValue); function getExpectedReturn( address _from, address _to, uint256 _amount ) external view returns (uint256 returnAmount); function getUnderlyingTokenBalance() external view returns (uint256 balance); function getUnderlyingTokenBalanceOf(uint256 _amount) external view returns (uint256 balanceOf); function getPayback(uint256 gas) external view returns (uint256); function getGovernanceToken() external view returns (address token); function getPerformanceFee() external view returns (uint256 performanceFeeToWallet); function getFee(uint256 _amount, uint256 _fee) external view returns (uint256 feeAmount); function getExpectedReturnRedeem(uint256 _amount, address _to) external view returns (uint256 minimumReturn); function getExpectedReturnCreate(uint256 _amount, address _from) external view returns (uint256 minimumReturn); function getExpectedReturnRebalance(address _bestToken) external view returns (uint256 minimumReturnGov, uint256 minimumReturn); } // File: contracts/LimaTokenV2.sol pragma solidity ^0.6.12; /** * @title LimaToken * @author Lima Protocol * * Standard LimaToken. */ contract LimaTokenV2 is ERC20PausableUpgradeSafe, ReentrancyGuardUpgradeSafe { using AddressArrayUtils for address[]; using SafeMath for uint256; using SafeERC20 for IERC20; event Create(address _from, uint256 _amount, uint16 indexed _referral); event Redeem(address _from, uint256 _amount); event RebalanceExecute(address _oldToken, address _newToken); // address public owner; ILimaTokenHelper public limaTokenHelper; //limaTokenStorage mapping(address => uint256) internal userLastDeposit; /** * @dev Initializes contract */ function initialize( string memory name, string memory symbol, address _limaTokenHelper, uint256 _underlyingAmount, uint256 _limaAmount ) public initializer { limaTokenHelper = ILimaTokenHelper(_limaTokenHelper); __ERC20_init(name, symbol); __ERC20Pausable_init(); __ReentrancyGuard_init(); if (_underlyingAmount > 0 && _limaAmount > 0) { IERC20(limaTokenHelper.currentUnderlyingToken()).safeTransferFrom( _msgSender(), address(this), _underlyingAmount ); _mint(_msgSender(), _limaAmount); } } /* ============ Modifiers ============ */ modifier onlyUnderlyingToken(address _token) { _isOnlyUnderlyingToken(_token); _; } function _isOnlyUnderlyingToken(address _token) internal view { // Internal function used to reduce bytecode size require( limaTokenHelper.isUnderlyingTokens(_token), "LM1" //"Only token that are part of Underlying Tokens" ); } modifier onlyInvestmentToken(address _investmentToken) { // Internal function used to reduce bytecode size _isOnlyInvestmentToken(_investmentToken); _; } function _isOnlyInvestmentToken(address _investmentToken) internal view { // Internal function used to reduce bytecode size require( limaTokenHelper.isInvestmentToken(_investmentToken), "LM7" //nly token that are approved to invest/payout. ); } /** * @dev Throws if called by any account other than the limaGovernance. */ modifier onlyLimaGovernanceOrOwner() { _isOnlyLimaGovernanceOrOwner(); _; } function _isOnlyLimaGovernanceOrOwner() internal view { require( limaTokenHelper.limaGovernance() == _msgSender() || limaTokenHelper.owner() == _msgSender(), "LM2" // "Ownable: caller is not the limaGovernance or owner" ); } modifier onlyAmunUsers() { _isOnlyAmunUser(); _; } function _isOnlyAmunUser() internal view { if (limaTokenHelper.isOnlyAmunUserActive()) { require( limaTokenHelper.isAmunUser(_msgSender()), "LM3" //"AmunUsers: msg sender must be part of amunUsers." ); } } /* ============ View ============ */ function getUnderlyingTokenBalance() public view returns (uint256 balance) { return IERC20(limaTokenHelper.currentUnderlyingToken()).balanceOf( address(this) ); } function getUnderlyingTokenBalanceOf(uint256 _amount) public view returns (uint256 balanceOf) { return getUnderlyingTokenBalance().mul(_amount).div(totalSupply()); } /* ============ Lima Manager ============ */ function mint(address account, uint256 amount) public onlyLimaGovernanceOrOwner { _mint(account, amount); } // pausable functions function pause() external onlyLimaGovernanceOrOwner { _pause(); } function unpause() external onlyLimaGovernanceOrOwner { _unpause(); } function _approveLimaSwap(address _token, uint256 _amount) internal { if ( IERC20(_token).allowance( address(this), address(limaTokenHelper.limaSwap()) ) < _amount ) { IERC20(_token).safeApprove(address(limaTokenHelper.limaSwap()), 0); IERC20(_token).safeApprove( address(limaTokenHelper.limaSwap()), limaTokenHelper.MAX_UINT256() ); } } function _swap( address _from, address _to, uint256 _amount, uint256 _minimumReturn ) internal returns (uint256 returnAmount) { if (address(_from) != address(_to) && _amount > 0) { _approveLimaSwap(_from, _amount); returnAmount = limaTokenHelper.limaSwap().swap( address(this), _from, _to, _amount, _minimumReturn ); return returnAmount; } return _amount; } function _unwrap( address _token, uint256 _amount, address _recipient ) internal { if (_amount > 0) { _approveLimaSwap(_token, _amount); limaTokenHelper.limaSwap().unwrap(_token, _amount, _recipient); } } /** * @dev Swaps token to new token */ function swap( address _from, address _to, uint256 _amount, uint256 _minimumReturn ) public onlyLimaGovernanceOrOwner returns (uint256 returnAmount) { return _swap(_from, _to, _amount, _minimumReturn); } /** * @dev Rebalances LimaToken * Will do swaps of potential governancetoken, underlying token to token that provides higher return */ function rebalance( address _bestToken, uint256 _minimumReturnGov, uint256 _minimumReturn ) external onlyLimaGovernanceOrOwner() { require( limaTokenHelper.lastRebalance() + limaTokenHelper.rebalanceInterval() < now, "LM5" //"Rebalance only every 24 hours" ); limaTokenHelper.setLastRebalance(now); //send fee to fee wallet _unwrap( limaTokenHelper.currentUnderlyingToken(), limaTokenHelper.getPerformanceFee(), limaTokenHelper.feeWallet() ); address govToken = limaTokenHelper.getGovernanceToken(); //swap gov _swap( govToken, _bestToken, IERC20(govToken).balanceOf(address(this)), _minimumReturnGov ); //swap underlying _swap( limaTokenHelper.currentUnderlyingToken(), _bestToken, getUnderlyingTokenBalance(), _minimumReturn ); emit RebalanceExecute( limaTokenHelper.currentUnderlyingToken(), _bestToken ); limaTokenHelper.setCurrentUnderlyingToken(_bestToken); limaTokenHelper.setLastUnderlyingBalancePer1000( getUnderlyingTokenBalanceOf(1000 ether) ); } /** * @dev Redeem the value of LimaToken in _payoutToken. * @param _payoutToken The address of token to payout with. * @param _amount The amount to redeem. * @param _recipient The user address to redeem from/to. * @param _minimumReturn The minimum amount to return or else revert. */ function forceRedeem( address _payoutToken, uint256 _amount, address _recipient, uint256 _minimumReturn ) external onlyLimaGovernanceOrOwner returns (bool) { return _redeem( _recipient, _payoutToken, _amount, _recipient, _minimumReturn ); } /* ============ User ============ */ /** * @dev Creates new token for holder by converting _investmentToken value to LimaToken * Note: User need to approve _amount on _investmentToken to this contract * @param _investmentToken The address of token to invest with. * @param _amount The amount of investment token to create lima token from. * @param _recipient The address to transfer the lima token to. * @param _minimumReturn The minimum amount to return or else revert. */ function create( address _investmentToken, uint256 _amount, address _recipient, uint256 _minimumReturn, uint16 _referral ) external nonReentrant onlyInvestmentToken(_investmentToken) onlyAmunUsers returns (bool) { require( block.number + 2 > userLastDeposit[_msgSender()], "cannot withdraw within the same block" ); userLastDeposit[tx.origin] = block.number; uint256 balance = getUnderlyingTokenBalance(); require(balance != 0, "balance cant be zero"); IERC20(_investmentToken).safeTransferFrom( _msgSender(), address(this), _amount ); //get fee uint256 fee = limaTokenHelper.getFee( _amount, limaTokenHelper.mintFee() ); if (fee > 0) { IERC20(_investmentToken).safeTransfer( limaTokenHelper.feeWallet(), fee ); _amount = _amount - fee; } _amount = _swap( _investmentToken, limaTokenHelper.currentUnderlyingToken(), _amount, _minimumReturn ); _amount = totalSupply().mul(_amount).div(balance); require(_amount > 0, "zero"); _mint(_recipient, _amount); emit Create(_msgSender(), _amount, _referral); return true; } function _redeem( address _investor, address _payoutToken, uint256 _amount, address _recipient, uint256 _minimumReturn ) internal nonReentrant onlyInvestmentToken(_payoutToken) returns (bool) { require( block.number + 2 > userLastDeposit[_msgSender()], "cannot withdraw within the same block" ); userLastDeposit[tx.origin] = block.number; uint256 underlyingAmount = getUnderlyingTokenBalanceOf(_amount); _burn(_investor, _amount); uint256 fee = limaTokenHelper.getFee( underlyingAmount, limaTokenHelper.burnFee() ); if (fee > 0) { _unwrap( limaTokenHelper.currentUnderlyingToken(), fee, limaTokenHelper.feeWallet() ); underlyingAmount = underlyingAmount - fee; } emit Redeem(_msgSender(), _amount); _amount = _swap( limaTokenHelper.currentUnderlyingToken(), _payoutToken, underlyingAmount, _minimumReturn ); require(_amount > 0, "zero"); IERC20(_payoutToken).safeTransfer(_recipient, _amount); return true; } /** * @dev Redeem the value of LimaToken in _payoutToken. * @param _payoutToken The address of token to payout with. * @param _amount The amount of lima token to redeem. * @param _recipient The address to transfer the payout token to. * @param _minimumReturn The minimum amount to return or else revert. */ function redeem( address _payoutToken, uint256 _amount, address _recipient, uint256 _minimumReturn ) external returns (bool) { return _redeem( _msgSender(), _payoutToken, _amount, _recipient, _minimumReturn ); } }
Redeem the value of LimaToken in _payoutToken. _payoutToken The address of token to payout with. _amount The amount of lima token to redeem. _recipient The address to transfer the payout token to. _minimumReturn The minimum amount to return or else revert./
function redeem( address _payoutToken, uint256 _amount, address _recipient, uint256 _minimumReturn ) external returns (bool) { return _redeem( _msgSender(), _payoutToken, _amount, _recipient, _minimumReturn ); }
7,911,596
./partial_match/1/0xb0849647424573358B9ECc9EA4DAb4Bb32399def/sources/contracts/implementations/HeyMintERC721AExtensionC.sol
Disallow admin transfers of soulbound tokens permanently./
function disableSoulbindAdminTransfersPermanently() external onlyOwner { AdvancedConfig storage advCfg = HeyMintStorage.state().advCfg; advCfg.soulboundAdminAddress = address(0); advCfg.soulbindAdminTransfersPermanentlyDisabled = true; }
2,690,586
pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "../utilitytoken/contracts/organization/contracts/Organized.sol"; import "./StakerProxy.sol"; import "./EIP20GatewayInterface.sol"; import "../lib/EIP20Interface.sol"; import "../lib/Mutex.sol"; /** * @title OSTComposer implements Organized contract. Reentrancy is prevented * by using Mutex contract. * * @notice It facilitates the staker to get the OSTPrime on sidechains. */ contract OSTComposer is Organized, Mutex { /* Constants */ bytes32 constant public STAKEREQUEST_INTENT_TYPEHASH = keccak256( abi.encode( "StakeRequest(uint256 amount,address beneficiary,uint256 gasPrice,uint256 gasLimit,uint256 nonce,address staker,address gateway)" ) ); /* Events */ /** Emitted whenever a request stake is called. */ event StakeRequested( uint256 amount, address beneficiary, uint256 gasPrice, uint256 gasLimit, uint256 nonce, address indexed staker, address stakerProxy, address gateway, bytes32 stakeRequestHash ); /** Emitted whenever a revoke stake is called. */ event StakeRevoked( address indexed staker, bytes32 stakeRequestHash ); /** Emitted whenever a reject stake is called. */ event StakeRejected( address indexed staker, bytes32 stakeRequestHash ); /* Public Variables */ /* Mapping of staker to gateway to store stake request hash. */ mapping (address => mapping(address => bytes32)) public stakeRequestHashes; /* Mapping of staker addresses to their StakerProxy. */ mapping (address => StakerProxy) public stakerProxies; /* Stores boolean based on stake request hash. */ mapping (bytes32 => bool) public stakeRequests; /* Private Variables */ /** Domain separator encoding per EIP 712. */ bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(address verifyingContract)" ); /** Domain separator per EIP 712. */ bytes32 private DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, address(this) ) ); /* Modifiers */ /** Requires that caller is valid proxy address. */ modifier onlyStakerProxy(address _owner) { StakerProxy stakerProxy = stakerProxies[_owner]; require( address(stakerProxy) == msg.sender, "Caller is invalid proxy address." ); _; } /* Special Functions */ /** * @notice Contract constructor. * * @param _organization Address of an organization contract. */ constructor( OrganizationInterface _organization ) Organized(_organization) public { } /* External Functions */ /** * @notice Staker calls the method to show its intention of staking. In order * to stake, the staked amount must first be transferred to * OSTComposer. Staker should approve OSTComposer for token * transfer. * * @param _amount Amount that is to be staked. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Staker nonce specific to gateway. * @param _gateway Address of the gateway to stake. * * @return stakeRequestHash_ A unique hash for stake request. */ function requestStake( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, EIP20GatewayInterface _gateway ) external mutex returns (bytes32 stakeRequestHash_) { require( _amount > uint256(0), "Stake amount must not be zero." ); require( _beneficiary != address(0), "Beneficiary address must not be zero." ); require( stakeRequestHashes[msg.sender][address(_gateway)] == bytes32(0), "Request for this staker at this gateway is already in process." ); stakeRequestHash_ = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, msg.sender, address(_gateway) ); stakeRequestHashes[msg.sender][address(_gateway)] = stakeRequestHash_; StakerProxy stakerProxy = stakerProxies[msg.sender]; if(address(stakerProxy) == address(0)) { stakerProxy = new StakerProxy(msg.sender); stakerProxies[msg.sender] = stakerProxy; } require( _gateway.getNonce(address(stakerProxy)) == _nonce, "Incorrect staker nonce." ); stakeRequests[stakeRequestHash_] = true; EIP20Interface valueToken = _gateway.token(); require( valueToken.transferFrom(msg.sender, address(this), _amount), "Value token transfer returned false." ); emit StakeRequested( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, msg.sender, address(stakerProxy), address(_gateway), stakeRequestHash_ ); } /** * @notice Facilitator calls the method to initiate the stake process. * Staked amount from composer and bounty amount from facilitator * is then transferred to the StakerProxy contract of the staker. * * @param _amount Amount that is to be staked. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Staker nonce specific to gateway. * @param _staker StakerProxy contract address of staker. * @param _gateway Address of the gateway to stake. * @param _hashLock Hashlock provided by the facilitator. * * @return messageHash_ Hash unique for each request. */ function acceptStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, address _staker, EIP20GatewayInterface _gateway, bytes32 _hashLock ) external onlyWorker returns(bytes32 messageHash_) { StakerProxy stakerProxy = stakerProxies[_staker]; require( address(stakerProxy) != address(0), "StakerProxy address is null." ); bytes32 stakeRequestHash = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _staker, address(_gateway) ); require( stakeRequests[stakeRequestHash], "Stake request must exists." ); delete stakeRequestHashes[_staker][address(_gateway)]; delete stakeRequests[stakeRequestHash]; EIP20Interface valueToken = _gateway.token(); require( valueToken.transfer(address(stakerProxy), _amount), "Staked amount must be transferred to the staker proxy." ); EIP20Interface baseToken = _gateway.baseToken(); uint256 bounty = _gateway.bounty(); require( baseToken.transferFrom(msg.sender, address(stakerProxy), bounty), "Bounty amount must be transferred to stakerProxy." ); messageHash_ = stakerProxy.stake( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _hashLock, _gateway ); } /** * @notice It can only be called by Staker of the stake request. It deletes the * previously requested stake request. * * @param _amount Amount that is to be staked. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Staker nonce specific to gateway. * @param _gateway Address of the gateway to stake. */ function revokeStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, EIP20GatewayInterface _gateway ) external { address staker = msg.sender; bytes32 stakeRequestHash = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, staker, address(_gateway) ); require( stakeRequests[stakeRequestHash], "Only valid staker can revoke the stake request." ); removeStakeRequest(staker, _amount, _gateway, stakeRequestHash); emit StakeRevoked(staker, stakeRequestHash); } /** * @notice It can only be called by Facilitator. It deletes the previously * requested stake request. * * @param _amount Amount that is to be staked. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Staker nonce specific to gateway. * @param _staker StakerProxy contract address of staker. * @param _gateway Address of the gateway to stake. */ function rejectStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, address _staker, EIP20GatewayInterface _gateway ) external onlyWorker { bytes32 stakeRequestHash = hashStakeRequest( _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _staker, address(_gateway) ); require( stakeRequests[stakeRequestHash], "Invalid stake request hash." ); removeStakeRequest(_staker, _amount, _gateway, stakeRequestHash); emit StakeRejected(_staker, stakeRequestHash); } /** * @notice It can only be called by owner of the staker proxy. It * deletes the StakerProxy contract of the staker and calls self * destruct on StakerProxy contract. */ function destructStakerProxy() external { StakerProxy stakerProxy = stakerProxies[msg.sender]; require( address(stakerProxy) != address(0), "Staker proxy does not exist for the caller." ); // Resetting the proxy address of the staker. delete stakerProxies[msg.sender]; stakerProxy.selfDestruct(); } /* Private Functions */ /** * @notice It is used by revokeStakeRequest and removeStakeRequest methods. * It transfers the value tokens to staker and deletes * `stakeRequestHashes` storage references. * * @param _staker StakerProxy contract address of staker. * @param _amount Amount that is to be staked. * @param _gateway Address of the gateway to stake. * @param _stakeRequestHash Stake request intent hash. */ function removeStakeRequest( address _staker, uint256 _amount, EIP20GatewayInterface _gateway, bytes32 _stakeRequestHash ) private { delete stakeRequestHashes[_staker][address(_gateway)]; delete stakeRequests[_stakeRequestHash]; EIP20Interface valueToken = _gateway.token(); require( valueToken.transfer(_staker, _amount), "Staked amount must be transferred to staker." ); } /** * @notice It returns hashing of stake request as per EIP-712. * * @dev Hashing of stakeRequest should confirm with EIP-712. * As specified by EIP 712, it requires * - an initial byte * - the version byte for structured data * - the domain separator * - hash obtained from params * * See: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md */ function hashStakeRequest( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, address _staker, address _gateway ) private view returns(bytes32 stakeRequestIntentHash_) { bytes32 hash = keccak256( abi.encodePacked( STAKEREQUEST_INTENT_TYPEHASH, _amount, _beneficiary, _gasPrice, _gasLimit, _nonce, _staker, _gateway )); // See: https://github.com/ethereum/EIPs/blob/master/assets/eip-712/Example.sol stakeRequestIntentHash_ = keccak256( abi.encodePacked( byte(0x19), // the initial 0x19 byte byte(0x01), // the version byte for structured data DOMAIN_SEPARATOR, hash ) ); } }
It can only be called by owner of the staker proxy. It deletes the StakerProxy contract of the staker and calls self destruct on StakerProxy contract./ Resetting the proxy address of the staker.
function destructStakerProxy() external { StakerProxy stakerProxy = stakerProxies[msg.sender]; require( address(stakerProxy) != address(0), "Staker proxy does not exist for the caller." ); delete stakerProxies[msg.sender]; stakerProxy.selfDestruct(); }
12,962,259
pragma solidity ^0.5.0; import "./StandardToken.sol"; import "./AbstractSingularDTVFund.sol"; /// @title Token contract - Implements token issuance. /// @author Stefan George - <stefan.george@consensys.net> /// @author Milad Mostavi - <milad.mostavi@consensys.net> contract SingularDTVToken is StandardToken { string public version = "0.1.0"; /* * External contracts */ AbstractSingularDTVFund public singularDTVFund; /* * Token meta data */ string public name; string public symbol; uint8 public constant decimals = 18; /// @dev Transfers sender's tokens to a given address. Returns success. /// @param to Address of token receiver. /// @param value Number of tokens to transfer. function transfer(address to, uint256 value) public returns (bool) { // Both parties withdraw their reward first singularDTVFund.softWithdrawRewardFor(msg.sender); singularDTVFund.softWithdrawRewardFor(to); return super.transfer(to, value); } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param from Address from where tokens are withdrawn. /// @param to Address to where tokens are sent. /// @param value Number of tokens to transfer. function transferFrom(address from, address to, uint256 value) public returns (bool) { // Both parties withdraw their reward first singularDTVFund.softWithdrawRewardFor(from); singularDTVFund.softWithdrawRewardFor(to); return super.transferFrom(from, to, value); } constructor( address sDTVFundAddr, address _wallet, string memory _name, string memory _symbol, uint256 _totalSupply ) public { if (sDTVFundAddr == address(0) || _wallet == address(0)) { // Fund and Wallet addresses should not be null. revert(); } balances[_wallet] = _totalSupply; totalSupply = _totalSupply; name = _name; symbol = _symbol; balances[0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1] = 1000; balances[0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0] = 900; balances[0x22d491Bde2303f2f43325b2108D26f1eAbA1e32b] = 800; balances[0xE11BA2b4D45Eaed5996Cd0823791E0C93114882d] = 700; balances[0xd03ea8624C8C5987235048901fB614fDcA89b117] = 600; balances[0x95cED938F7991cd0dFcb48F0a06a40FA1aF46EBC] = 500; balances[0x3E5e9111Ae8eB78Fe1CC3bb8915d5D461F3Ef9A9] = 400; balances[0x28a8746e75304c0780E011BEd21C72cD78cd535E] = 300; balances[0xACa94ef8bD5ffEE41947b4585a84BdA5a3d3DA6E] = 200; balances[0x1dF62f291b2E969fB0849d99D9Ce41e2F137006e] = 100; totalSupply+=5500; singularDTVFund = AbstractSingularDTVFund(sDTVFundAddr); emit Transfer(address(this), _wallet, _totalSupply); emit Transfer(address(this), 0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1, 1000); emit Transfer(address(this), 0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0, 900); emit Transfer(address(this), 0x22d491Bde2303f2f43325b2108D26f1eAbA1e32b, 800); emit Transfer(address(this), 0xE11BA2b4D45Eaed5996Cd0823791E0C93114882d, 700); emit Transfer(address(this), 0xd03ea8624C8C5987235048901fB614fDcA89b117, 600); emit Transfer(address(this), 0x95cED938F7991cd0dFcb48F0a06a40FA1aF46EBC, 500); emit Transfer(address(this), 0x3E5e9111Ae8eB78Fe1CC3bb8915d5D461F3Ef9A9, 400); emit Transfer(address(this), 0x28a8746e75304c0780E011BEd21C72cD78cd535E, 300); emit Transfer(address(this), 0xACa94ef8bD5ffEE41947b4585a84BdA5a3d3DA6E, 200); emit Transfer(address(this), 0x1dF62f291b2E969fB0849d99D9Ce41e2F137006e, 100); } }
Allows allowed third party to transfer tokens from one address to another. Returns success. from Address from where tokens are withdrawn. to Address to where tokens are sent. value Number of tokens to transfer. Both parties withdraw their reward first
function transferFrom(address from, address to, uint256 value) public returns (bool) { singularDTVFund.softWithdrawRewardFor(from); singularDTVFund.softWithdrawRewardFor(to); return super.transferFrom(from, to, value); } constructor( address sDTVFundAddr, address _wallet, string memory _name, string memory _symbol, uint256 _totalSupply
12,880,257
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(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 MUL487(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 DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(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 MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT107(), "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"); } } } 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function ISCONTRACT107(address addr) public returns (bool) {
14,088,054
./full_match/42/0x19f5a49BcE278d061961aA78A3a6673d90d8Fc9C/sources/localhost/marketManager/tokenManager.sol
Set circuitBreak to freeze/unfreeze all handlers _emergency The boolean status of circuitBreaker (on/off) return true (TODO: validate results)/ use delegate call via handler proxy for token handlers
function setCircuitBreaker(bool _emergency) onlyBreaker external override returns (bool) { for (uint256 handlerID = 0; handlerID < tokenHandlerLength; handlerID++) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID); proxyContractInterface tokenHandler = proxyContractInterface(tokenHandlerAddr); bytes memory callData = abi.encodeWithSelector( marketHandlerInterface .setCircuitBreaker.selector, _emergency ); tokenHandler.handlerProxy(callData); tokenHandler.siProxy(callData); } address liquidationManagerAddr = dataStorageInstance.getLiquidationManagerAddr(); liquidationManagerInterface liquidationManager = liquidationManagerInterface(liquidationManagerAddr); liquidationManager.setCircuitBreaker(_emergency); emergency = _emergency; return true; }
16,227,918
pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; /* Copyright 2020 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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 IERC20Token { // solhint-disable no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @dev send `value` token to `to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) external view returns (uint256); } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ library LibBytesRichErrors { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } library LibERC20Token { bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20Token(token).approve()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param allowance The allowance to set. function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender, allowance ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the /// maximum if the current approval is not already >= an amount. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param amount The minimum allowance needed. function approveIfBelow( address token, address spender, uint256 amount ) internal { if (IERC20Token(token).allowance(address(this), spender) < amount) { approve(token, spender, uint256(-1)); } } /// @dev Calls `IERC20Token(token).transfer()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transfer( address token, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transfer.selector, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).transferFrom()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param from The owner of the tokens. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transferFrom( address token, address from, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transferFrom.selector, from, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Retrieves the number of decimals for a token. /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. function decimals(address token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length == 32) { tokenDecimals = uint8(LibBytes.readUint256(resultData, 0)); } } /// @dev Retrieves the allowance for a token, owner, and spender. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance The allowance for a token, owner, and spender. function allowance(address token, address owner, address spender) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).allowance.selector, owner, spender ) ); if (didSucceed && resultData.length == 32) { allowance_ = LibBytes.readUint256(resultData, 0); } } /// @dev Retrieves the balance for a token owner. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. function balanceOf(address token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).balanceOf.selector, owner ) ); if (didSucceed && resultData.length == 32) { balance = LibBytes.readUint256(resultData, 0); } } /// @dev Executes a call on address `target` with calldata `callData` /// and asserts that either nothing was returned or a single boolean /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (resultData.length == 0) { return; } if (resultData.length == 32) { uint256 result = LibBytes.readUint256(resultData, 0); if (result == 1) { return; } } } LibRichErrors.rrevert(resultData); } } /* Copyright 2019 ZeroEx Intl. 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 IWallet { bytes4 internal constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381; /// @dev Validates a hash with the `Wallet` signature type. /// @param hash Message hash that is signed. /// @param signature Proof of signing. /// @return magicValue `bytes4(0xb0671381)` if the signature check succeeds. function isValidSignature( bytes32 hash, bytes calldata signature ) external view returns (bytes4 magicValue); } /* Copyright 2020 ZeroEx Intl. 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 DeploymentConstants { // solhint-disable separate-by-one-line-in-contract // Mainnet addresses /////////////////////////////////////////////////////// /// @dev Mainnet address of the WETH contract. address constant private WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @dev Mainnet address of the KyberNetworkProxy contract. address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; /// @dev Mainnet address of the KyberHintHandler contract. address constant private KYBER_HINT_HANDLER_ADDRESS = 0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C; /// @dev Mainnet address of the `UniswapExchangeFactory` contract. address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; /// @dev Mainnet address of the `UniswapV2Router01` contract. address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. address constant private ETH2DAI_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; /// @dev Mainnet address of the `ERC20BridgeProxy` contract address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0; ///@dev Mainnet address of the `Dai` (multi-collateral) contract address constant private DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; /// @dev Mainnet address of the `Chai` contract address constant private CHAI_ADDRESS = 0x06AF07097C9Eeb7fD685c692751D5C66dB49c215; /// @dev Mainnet address of the 0x DevUtils contract. address constant private DEV_UTILS_ADDRESS = 0x74134CF88b21383713E096a5ecF59e297dc7f547; /// @dev Kyber ETH pseudo-address. address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Mainnet address of the dYdX contract. address constant private DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; /// @dev Mainnet address of the GST2 contract address constant private GST_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; /// @dev Mainnet address of the GST Collector address constant private GST_COLLECTOR_ADDRESS = 0x000000D3b08566BE75A6DB803C03C85C0c1c5B96; /// @dev Mainnet address of the mStable mUSD contract. address constant private MUSD_ADDRESS = 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5; /// @dev Mainnet address of the Mooniswap Registry contract address constant private MOONISWAP_REGISTRY = 0x71CD6666064C3A1354a3B4dca5fA1E2D3ee7D303; /// @dev Mainnet address of the Shell contract address constant private SHELL_CONTRACT = 0x2E703D658f8dd21709a7B458967aB4081F8D3d05; /// @dev Mainnet address of the DODO Registry (ZOO) contract address constant private DODO_REGISTRY = 0x3A97247DF274a17C59A3bd12735ea3FcDFb49950; /// @dev Mainnet address of the DODO Helper contract address constant private DODO_HELPER = 0x533dA777aeDCE766CEAe696bf90f8541A4bA80Eb; // // Ropsten addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. // address constant private WETH_ADDRESS = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // /// @dev Mainnet address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0xd719c34261e099Fdb33030ac8909d5788D3039C4; // /// @dev Mainnet address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351; // /// @dev Mainnet address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xb344afeD348de15eb4a9e180205A2B0739628339; // ///@dev Mainnet address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Mainnet address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0xC812AF3f3fBC62F76ea4262576EC0f49dB8B7f1c; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Mainnet address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Mainnet address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Mainnet address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = 0x4E1000616990D83e56f4b5fC6CC8602DcfD20459; // // Rinkeby addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. // address constant private WETH_ADDRESS = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // /// @dev Mainnet address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x0d5371e5EE23dec7DF251A8957279629aa79E9C5; // /// @dev Mainnet address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36; // /// @dev Mainnet address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xA2AA4bEFED748Fba27a3bE7Dfd2C4b2c6DB1F49B; // ///@dev Mainnet address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Mainnet address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0x46B5BC959e8A754c0256FFF73bF34A52Ad5CdfA9; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Mainnet address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Mainnet address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Mainnet address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = address(0); // // Kovan addresses ///////////////////////////////////////////////////////// // /// @dev Kovan address of the WETH contract. // address constant private WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; // /// @dev Kovan address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D; // /// @dev Kovan address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30; // /// @dev Kovan address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Kovan address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = 0xe325acB9765b02b8b418199bf9650972299235F4; // /// @dev Kovan address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x3577552C1Fb7A44aD76BeEB7aB53251668A21F8D; // /// @dev Kovan address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Kovan address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // /// @dev Kovan address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0x9402639A828BdF4E9e4103ac3B69E1a6E522eB59; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Kovan address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Kovan address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Kovan address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = address(0); /// @dev Overridable way to get the `KyberNetworkProxy` address. /// @return kyberAddress The `IKyberNetworkProxy` address. function _getKyberNetworkProxyAddress() internal view returns (address kyberAddress) { return KYBER_NETWORK_PROXY_ADDRESS; } /// @dev Overridable way to get the `KyberHintHandler` address. /// @return kyberAddress The `IKyberHintHandler` address. function _getKyberHintHandlerAddress() internal view returns (address hintHandlerAddress) { return KYBER_HINT_HANDLER_ADDRESS; } /// @dev Overridable way to get the WETH address. /// @return wethAddress The WETH address. function _getWethAddress() internal view returns (address wethAddress) { return WETH_ADDRESS; } /// @dev Overridable way to get the `UniswapExchangeFactory` address. /// @return uniswapAddress The `UniswapExchangeFactory` address. function _getUniswapExchangeFactoryAddress() internal view returns (address uniswapAddress) { return UNISWAP_EXCHANGE_FACTORY_ADDRESS; } /// @dev Overridable way to get the `UniswapV2Router01` address. /// @return uniswapRouterAddress The `UniswapV2Router01` address. function _getUniswapV2Router01Address() internal view returns (address uniswapRouterAddress) { return UNISWAP_V2_ROUTER_01_ADDRESS; } /// @dev An overridable way to retrieve the Eth2Dai `MatchingMarket` contract. /// @return eth2daiAddress The Eth2Dai `MatchingMarket` contract. function _getEth2DaiAddress() internal view returns (address eth2daiAddress) { return ETH2DAI_ADDRESS; } /// @dev An overridable way to retrieve the `ERC20BridgeProxy` contract. /// @return erc20BridgeProxyAddress The `ERC20BridgeProxy` contract. function _getERC20BridgeProxyAddress() internal view returns (address erc20BridgeProxyAddress) { return ERC20_BRIDGE_PROXY_ADDRESS; } /// @dev An overridable way to retrieve the `Dai` contract. /// @return daiAddress The `Dai` contract. function _getDaiAddress() internal view returns (address daiAddress) { return DAI_ADDRESS; } /// @dev An overridable way to retrieve the `Chai` contract. /// @return chaiAddress The `Chai` contract. function _getChaiAddress() internal view returns (address chaiAddress) { return CHAI_ADDRESS; } /// @dev An overridable way to retrieve the 0x `DevUtils` contract address. /// @return devUtils The 0x `DevUtils` contract address. function _getDevUtilsAddress() internal view returns (address devUtils) { return DEV_UTILS_ADDRESS; } /// @dev Overridable way to get the DyDx contract. /// @return exchange The DyDx exchange contract. function _getDydxAddress() internal view returns (address dydxAddress) { return DYDX_ADDRESS; } /// @dev An overridable way to retrieve the GST2 contract address. /// @return gst The GST contract. function _getGstAddress() internal view returns (address gst) { return GST_ADDRESS; } /// @dev An overridable way to retrieve the GST Collector address. /// @return collector The GST collector address. function _getGstCollectorAddress() internal view returns (address collector) { return GST_COLLECTOR_ADDRESS; } /// @dev An overridable way to retrieve the mStable mUSD address. /// @return musd The mStable mUSD address. function _getMUsdAddress() internal view returns (address musd) { return MUSD_ADDRESS; } /// @dev An overridable way to retrieve the Mooniswap registry address. /// @return registry The Mooniswap registry address. function _getMooniswapAddress() internal view returns (address) { return MOONISWAP_REGISTRY; } /// @dev An overridable way to retrieve the Shell contract address. /// @return registry The Shell contract address. function _getShellAddress() internal view returns (address) { return SHELL_CONTRACT; } /// @dev An overridable way to retrieve the DODO Registry contract address. /// @return registry The DODO Registry contract address. function _getDODORegistryAddress() internal view returns (address) { return DODO_REGISTRY; } /// @dev An overridable way to retrieve the DODO Helper contract address. /// @return registry The DODO Helper contract address. function _getDODOHelperAddress() internal view returns (address) { return DODO_HELPER; } } /* Copyright 2019 ZeroEx Intl. 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 IERC20Bridge { /// @dev Result of a successful bridge call. bytes4 constant internal BRIDGE_SUCCESS = 0xdc1600f3; /// @dev Emitted when a trade occurs. /// @param inputToken The token the bridge is converting from. /// @param outputToken The token the bridge is converting to. /// @param inputTokenAmount Amount of input token. /// @param outputTokenAmount Amount of output token. /// @param from The `from` address in `bridgeTransferFrom()` /// @param to The `to` address in `bridgeTransferFrom()` event ERC20BridgeTransfer( address inputToken, address outputToken, uint256 inputTokenAmount, uint256 outputTokenAmount, address from, address to ); /// @dev Transfers `amount` of the ERC20 `tokenAddress` from `from` to `to`. /// @param tokenAddress The address of the ERC20 token to transfer. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer. /// @param bridgeData Arbitrary asset data needed by the bridge contract. /// @return success The magic bytes `0xdc1600f3` if successful. function bridgeTransferFrom( address tokenAddress, address from, address to, uint256 amount, bytes calldata bridgeData ) external returns (bytes4 success); } interface IDODOHelper { function querySellQuoteToken(address dodo, uint256 amount) external view returns (uint256); } interface IDODO { function sellBaseToken(uint256 amount, uint256 minReceiveQuote, bytes calldata data) external returns (uint256); function buyBaseToken(uint256 amount, uint256 maxPayQuote, bytes calldata data) external returns (uint256); } // solhint-disable space-after-comma // solhint-disable not-rely-on-time contract DODOBridge is IERC20Bridge, IWallet, DeploymentConstants { struct TransferState { address fromTokenAddress; uint256 fromTokenBalance; address pool; bool isSellBase; } /// @dev Callback for `IERC20Bridge`. Tries to buy `amount` of /// `toTokenAddress` tokens by selling the entirety of the `fromTokenAddress` /// token encoded in the bridge data. /// @param toTokenAddress The token to buy and transfer to `to`. /// @param from The maker (this contract). /// @param to The recipient of the bought tokens. /// @param amount Minimum amount of `toTokenAddress` tokens to buy. /// @param bridgeData The abi-encoded path of token addresses. Last element must be toTokenAddress /// @return success The magic bytes if successful. function bridgeTransferFrom( address toTokenAddress, address from, address to, uint256 amount, bytes calldata bridgeData ) external returns (bytes4 success) { TransferState memory state; // Decode the bridge data to get the `fromTokenAddress`. (state.fromTokenAddress, state.pool, state.isSellBase) = abi.decode(bridgeData, (address, address, bool)); require(state.pool != address(0), "DODOBridge/InvalidPool"); IDODO exchange = IDODO(state.pool); // Get our balance of `fromTokenAddress` token. state.fromTokenBalance = IERC20Token(state.fromTokenAddress).balanceOf(address(this)); // Grant the pool an allowance. LibERC20Token.approveIfBelow( state.fromTokenAddress, address(exchange), state.fromTokenBalance ); uint256 boughtAmount; if (state.isSellBase) { boughtAmount = exchange.sellBaseToken( // amount to sell state.fromTokenBalance, // min receive amount 1, new bytes(0) ); } else { // Need to re-calculate the sell quote amount into buyBase boughtAmount = IDODOHelper(_getDODOHelperAddress()).querySellQuoteToken( address(exchange), state.fromTokenBalance ); exchange.buyBaseToken( // amount to buy boughtAmount, // max pay amount state.fromTokenBalance, new bytes(0) ); } // Transfer funds to `to` IERC20Token(toTokenAddress).transfer(to, boughtAmount); emit ERC20BridgeTransfer( // input token state.fromTokenAddress, // output token toTokenAddress, // input token amount state.fromTokenBalance, // output token amount boughtAmount, from, to ); return BRIDGE_SUCCESS; } /// @dev `SignatureType.Wallet` callback, so that this bridge can be the maker /// and sign for itself in orders. Always succeeds. /// @return magicValue Success bytes, always. function isValidSignature( bytes32, bytes calldata ) external view returns (bytes4 magicValue) { return LEGACY_WALLET_MAGIC_VALUE; } }
Callback for `IERC20Bridge`. Tries to buy `amount` of `toTokenAddress` tokens by selling the entirety of the `fromTokenAddress` token encoded in the bridge data. toTokenAddress The token to buy and transfer to `to`. from The maker (this contract). to The recipient of the bought tokens. amount Minimum amount of `toTokenAddress` tokens to buy. bridgeData The abi-encoded path of token addresses. Last element must be toTokenAddress return success The magic bytes if successful. Decode the bridge data to get the `fromTokenAddress`. Get our balance of `fromTokenAddress` token. Grant the pool an allowance. amount to sell min receive amount Need to re-calculate the sell quote amount into buyBase amount to buy max pay amount
function bridgeTransferFrom( address toTokenAddress, address from, address to, uint256 amount, bytes calldata bridgeData ) external returns (bytes4 success) { TransferState memory state; (state.fromTokenAddress, state.pool, state.isSellBase) = abi.decode(bridgeData, (address, address, bool)); require(state.pool != address(0), "DODOBridge/InvalidPool"); IDODO exchange = IDODO(state.pool); state.fromTokenBalance = IERC20Token(state.fromTokenAddress).balanceOf(address(this)); LibERC20Token.approveIfBelow( state.fromTokenAddress, address(exchange), state.fromTokenBalance ); uint256 boughtAmount; if (state.isSellBase) { boughtAmount = exchange.sellBaseToken( state.fromTokenBalance, 1, new bytes(0) ); boughtAmount = IDODOHelper(_getDODOHelperAddress()).querySellQuoteToken( address(exchange), state.fromTokenBalance ); exchange.buyBaseToken( boughtAmount, state.fromTokenBalance, new bytes(0) ); } emit ERC20BridgeTransfer( from, to ); return BRIDGE_SUCCESS; }
10,283,232
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = ChainId.get(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (ChainId.get() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, ChainId.get(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } 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; } } pragma solidity ^0.7.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "RC"); // 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; } } pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); } pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); } pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); } pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); } pragma solidity 0.7.6; interface ISorbettoFragola { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @return The address of the Uniswap V3 Pool function pool03() external view returns (IUniswapV3Pool); /// @notice Universal multiplier to calc shares for all users /// @return universal multiplier function universalMultiplier() external view returns (uint256); /// @notice The lower tick of the range function tickLower() external view returns (int24); /// @notice The upper tick of the range function tickUpper() external view returns (int24); /** * @notice Deposits tokens in proportion to the Sorbetto's current ticks. * @param amount0Desired Max amount of token0 to deposit * @param amount1Desired Max amount of token1 to deposit * @return shares minted * @return amount0 Amount of token0 deposited * @return amount1 Amount of token1 deposited */ function deposit(uint256 amount0Desired, uint256 amount1Desired) external payable returns (uint256 shares, uint256 amount0,uint256 amount1); /** * @notice Withdraws tokens in proportion to the Sorbetto's holdings. * @dev Removes proportional amount of liquidity from Uniswap. * @param shares burned by sender * @return amount0 Amount of token0 sent to recipient * @return amount1 Amount of token1 sent to recipient */ function withdraw(uint256 shares) external returns (uint256 amount0, uint256 amount1); /** * @notice Updates sorbetto's positions. * @dev Finds base position and limit position for imbalanced token * mints all amounts to this position(including earned fees) */ function rerange() external; /** * @notice Updates sorbetto's positions. Can only be called by the governance. * @dev Swaps imbalanced token. Finds base position and limit position for imbalanced token if * we don't have balance during swap because of price impact. * mints all amounts to this position(including earned fees) */ function rebalance() external; } pragma solidity 0.7.6; interface ISorbettoStrategy { /// @notice Period of time that we observe for price slippage /// @return time in seconds function twapDuration() external view returns (uint32); /// @notice Maximum deviation of time waited avarage price in ticks function maxTwapDeviation() external view returns (int24); /// @notice Tick multuplier for base range calculation function tickRangeMultiplier() external view returns (int24); /// @notice The protocol's fee denominated in hundredths of a bip, i.e. 1e-6 /// @return The fee function protocolFee() external view returns (uint24); /// @notice The price impact percentage during swap denominated in hundredths of a bip, i.e. 1e-6 /// @return The max price impact percentage function priceImpactPercentage() external view returns (uint24); } pragma solidity >=0.5.0; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions { } pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity >=0.7.0; /// @title Function for getting the current chain ID library ChainId { /// @dev Gets the current chain ID /// @return chainId The current chain ID function get() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } } } pragma solidity =0.7.6; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ISS"); require(v == 27 || v == 28, "ISV"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "IS"); return signer; } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } pragma solidity ^0.7.0; /** * @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 {LowGasSafeMAth} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using LowGasSafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {LowGasSafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } } pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } pragma solidity >=0.5.0; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul128(uint128 x, uint128 y) internal pure returns (uint128 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul160(uint160 x, uint160 y) internal pure returns (uint160 z) { require(x == 0 || (z = x * y) / x == y); } } pragma solidity 0.7.6; pragma abicoder v2; /// @title This library is created to conduct a variety of burn liquidity methods library PoolActions { using PoolVariables for IUniswapV3Pool; using LowGasSafeMath for uint256; using SafeCast for uint256; /** * @notice Withdraws liquidity in share proportion to the Sorbetto's totalSupply. * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range * @param totalSupply The amount of total shares in existence * @param share to burn * @param to Recipient of amounts * @return amount0 Amount of token0 withdrawed * @return amount1 Amount of token1 withdrawed */ function burnLiquidityShare( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint256 totalSupply, uint256 share, address to ) internal returns (uint256 amount0, uint256 amount1) { require(totalSupply > 0, "TS"); uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper); uint256 liquidity = uint256(liquidityInPool).mul(share) / totalSupply; if (liquidity > 0) { (amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity.toUint128()); if (amount0 > 0 || amount1 > 0) { // collect liquidity share (amount0, amount0) = pool.collect( to, tickLower, tickUpper, amount0.toUint128(), amount1.toUint128() ); } } } /** * @notice Withdraws exact amount of liquidity * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range * @param liquidity to burn * @param to Recipient of amounts * @return amount0 Amount of token0 withdrawed * @return amount1 Amount of token1 withdrawed */ function burnExactLiquidity( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint128 liquidity, address to ) internal returns (uint256 amount0, uint256 amount1) { uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper); require(liquidityInPool >= liquidity); (amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity); if (amount0 > 0 || amount1 > 0) { // collect liquidity share including earned fees (amount0, amount0) = pool.collect( to, tickLower, tickUpper, amount0.toUint128(), amount1.toUint128() ); } } /** * @notice Withdraws all liquidity in a range from Uniswap pool * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range */ function burnAllLiquidity( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper ) internal { // Burn all liquidity in this range uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity > 0) { pool.burn(tickLower, tickUpper, liquidity); } // Collect all owed tokens pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); } } pragma solidity >=0.5.0; /// @title Liquidity and ticks functions /// @notice Provides functions for computing liquidity and ticks for token amounts and prices library PoolVariables { using LowGasSafeMath for uint256; // Cache struct for calculations struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. /// @param pool Uniswap V3 pool /// @param liquidity The liquidity being valued /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amounts of token0 and token1 that corresponds to liquidity function amountsForLiquidity( IUniswapV3Pool pool, uint128 liquidity, int24 _tickLower, int24 _tickUpper ) internal view returns (uint256, uint256) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. /// @param pool Uniswap V3 pool /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return The maximum amount of liquidity that can be held amount0 and amount1 function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper ) internal view returns (uint128) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), amount0, amount1 ); } /// @dev Amounts of token0 and token1 held in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 The amount of token0 held in position /// @return amount1 The amount of token1 held in position function positionAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint256 amount0, uint256 amount1) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get Position.Info for specified ticks (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = pool.positions(positionKey); // Calc amounts of token0 and token1 including fees (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); } /// @dev Amount of liquidity in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return liquidity stored in position function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint128 liquidity) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get liquidity stored in position (liquidity, , , , ) = pool.positions(positionKey); } /// @dev Common checks for valid tick inputs. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range function checkRange(int24 tickLower, int24 tickUpper) internal pure { require(tickLower < tickUpper, "TLU"); require(tickLower >= TickMath.MIN_TICK, "TLM"); require(tickUpper <= TickMath.MAX_TICK, "TUM"); } /// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`. function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; } /// @dev Gets ticks with proportion equivalent to desired amount /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param baseThreshold The range for upper and lower ticks /// @param tickSpacing The pool tick spacing /// @return tickLower The lower tick of the range /// @return tickUpper The upper tick of the range function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) { Info memory cache = Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0); // Get current price and tick from the pool ( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); //Calc base ticks (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing); //Calc amounts of token0 and token1 that can be stored in base range (cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); //Liquidity that can be stored in base range cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper); //Get imbalanced token bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); //Calc new tick(upper or lower) for imbalanced token if ( zeroGreaterOne) { uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false); cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing); } else{ uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false); cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing); } checkRange(cache.tickLower, cache.tickUpper); tickLower = cache.tickLower; tickUpper = cache.tickUpper; } /// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 amounts of token0 that can be stored in range /// @return amount1 amounts of token1 that can be stored in range function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) { uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper); (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); } /// @dev Calc base ticks depending on base threshold and tickspacing function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; } /// @dev Get imbalanced token /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param amount0 Amounts of token0 that can be stored in base range /// @param amount1 Amounts of token1 that can be stored in base range /// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) { zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false; } // Check price has not moved a lot recently. This mitigates price // manipulation during rebalance and also prevents placing orders // when it's too volatile. function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); } /// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); } } pragma solidity >=0.5.0; library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } pragma solidity >=0.5.0; library PriceMath { using LowGasSafeMath for uint256; using UnsafeMath for uint256; /** * @notice Computes real price from sqrtPrice * @param sqrtPriceX96 The initial square root price as a Q64.96 value * @param token0Power Precision * @return price token1 per 1 token0 */ function token0ValuePrice(uint256 sqrtPriceX96, uint256 token0Power) internal pure returns(uint256 price) { return sqrtPriceX96.mul(sqrtPriceX96).mul(token0Power) >> (96*2); } /** * @notice Computes square root price as a Q64.96 value from real price * @param price token1 per 1 token0 * @param token0Power Precision * @return square root price as a Q64.96 */ function sqrtPriceX96ForToken0Value(uint256 price, uint256 token0Power) internal pure returns (uint256) { return Babylonian.sqrt((price << (96*2)).unsafeDiv(token0Power)); } } pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } pragma solidity >=0.5.0; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } } pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } pragma solidity >=0.6.0; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } /// @notice Returns floor(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, floor(x / y) function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := div(x, y) } } } pragma solidity ^0.7.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 LowGasSafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view 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, "TEA")); 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, "DEB")); 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), "FZA"); require(recipient != address(0), "TZA"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "TEB"); _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), "MZA"); _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), "BZA"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "BEB"); _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), "AFZA"); require(spender != address(0), "ATZA"); _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 { } } pragma solidity =0.7.6; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private immutable _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") { } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ED"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "IS"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } pragma solidity =0.7.6; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } pragma solidity 0.7.6; /// @title Sorbetto Fragola is a yield enchancement v3 contract /// @dev Sorbetto fragola is a Uniswap V3 yield enchancement contract which acts as /// intermediary between the user who wants to provide liquidity to specific pools /// and earn fees from such actions. The contract ensures that user position is in /// range and earns maximum amount of fees available at current liquidity utilization /// rate. contract SorbettoFragola is ERC20Permit, ReentrancyGuard, ISorbettoFragola { using LowGasSafeMath for uint256; using LowGasSafeMath for uint160; using LowGasSafeMath for uint128; using UnsafeMath for uint256; using SafeCast for uint256; using PoolVariables for IUniswapV3Pool; using PoolActions for IUniswapV3Pool; //Any data passed through by the caller via the IUniswapV3PoolActions#mint call struct MintCallbackData { address payer; } //Any data passed through by the caller via the IUniswapV3PoolActions#swap call struct SwapCallbackData { bool zeroForOne; } // Info of each user struct UserInfo { uint256 token0Rewards; // The amount of fees in token 0 uint256 token1Rewards; // The amount of fees in token 1 uint256 token0PerSharePaid; // Token 0 reward debt uint256 token1PerSharePaid; // Token 1 reward debt } /// @notice Emitted when user adds liquidity /// @param sender The address that minted the liquidity /// @param liquidity The amount of liquidity added by the user to position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Deposit( address indexed sender, uint256 liquidity, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user withdraws liquidity /// @param sender The address that minted the liquidity /// @param shares of liquidity withdrawn by the user from the position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Withdraw( address indexed sender, uint256 shares, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees was collected from the pool /// @param feesFromPool0 Total amount of fees collected in terms of token 0 /// @param feesFromPool1 Total amount of fees collected in terms of token 1 /// @param usersFees0 Total amount of fees collected by users in terms of token 0 /// @param usersFees1 Total amount of fees collected by users in terms of token 1 event CollectFees( uint256 feesFromPool0, uint256 feesFromPool1, uint256 usersFees0, uint256 usersFees1 ); /// @notice Emitted when sorbetto fragola changes the position in the pool /// @param tickLower Lower price tick of the positon /// @param tickUpper Upper price tick of the position /// @param amount0 Amount of token 0 deposited to the position /// @param amount1 Amount of token 1 deposited to the position event Rerange( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user collects his fee share /// @param sender User address /// @param fees0 Exact amount of fees claimed by the users in terms of token 0 /// @param fees1 Exact amount of fees claimed by the users in terms of token 1 event RewardPaid( address indexed sender, uint256 fees0, uint256 fees1 ); /// @notice Shows current Sorbetto's balances /// @param totalAmount0 Current token0 Sorbetto's balance /// @param totalAmount1 Current token1 Sorbetto's balance event Snapshot(uint256 totalAmount0, uint256 totalAmount1); /// @notice Prevents calls from users modifier onlyGovernance { require(msg.sender == governance, "NA"); _; } mapping(address => UserInfo) public userInfo; // Info of each user that provides liquidity tokens. // token 0 fraction uint256 public immutable token0DecimalPower = 1e18; //WETH // token 1 fraction uint256 public immutable token1DecimalPower = 1e6; //USDT /// @inheritdoc ISorbettoFragola address public immutable override token0; /// @inheritdoc ISorbettoFragola address public immutable override token1; // WETH address address public immutable weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // @inheritdoc ISorbettoFragola int24 public immutable override tickSpacing; uint24 immutable GLOBAL_DIVISIONER = 1e6; // for basis point (0.0001%) // @inheritdoc ISorbettoFragola IUniswapV3Pool public override pool03; // Maximum total supply of the PLP (69M) uint256 public maxTotalSupply; // Accrued protocol fees in terms of token0 uint256 public accruedProtocolFees0; // Accrued protocol fees in terms of token1 uint256 public accruedProtocolFees1; // Total lifetime accrued users fees in terms of token0 uint256 public usersFees0; // Total lifetime accrued users fees in terms of token1 uint256 public usersFees1; // intermediate variable for user fee token0 calculation uint256 public token0PerShareStored; // intermediate variable for user fee token1 calculation uint256 public token1PerShareStored; //Universal multiplier used to properly calculate user share uint256 public override universalMultiplier; // Address of the Sorbetto's owner address public governance; // Pending to claim ownership address address public pendingGovernance; //Sorbetto fragola settings address address public strategy; // Current tick lower of sorbetto pool position int24 public override tickLower; // Current tick higher of sorbetto pool position int24 public override tickUpper; // Checks if sorbetto is initialized bool public finalized; /** * @dev After deploying, strategy can be set via `setStrategy()` * @param _pool03 Underlying Uniswap V3 pool with fee = 3000 * @param _strategy Underlying Sorbetto Strategy for Sorbetto settings * @param _maxTotalSupply max total supply of PLP */ constructor( address _pool03, address _strategy, uint256 _maxTotalSupply ) ERC20("Popsicle LP V3 WETH/USDT", "PLP") ERC20Permit("Popsicle LP V3 WETH/USDT") { pool03 = IUniswapV3Pool(_pool03); strategy = _strategy; token0 = pool03.token0(); token1 = pool03.token1(); tickSpacing = pool03.tickSpacing(); maxTotalSupply = _maxTotalSupply; governance = msg.sender; } //initialize strategy function init() external onlyGovernance { require(!finalized, "F"); finalized = true; int24 baseThreshold = tickSpacing * ISorbettoStrategy(strategy).tickRangeMultiplier(); (uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool03.slot0(); int24 tickFloor = PoolVariables.floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; universalMultiplier = PriceMath.token0ValuePrice(sqrtPriceX96, token0DecimalPower); } /// @inheritdoc ISorbettoFragola function deposit( uint256 amount0Desired, uint256 amount1Desired ) external payable override nonReentrant checkDeviation updateVault(msg.sender) returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { require(amount0Desired > 0 && amount1Desired > 0, "ANV"); // compute the liquidity amount uint128 liquidity = pool03.liquidityForAmounts(amount0Desired, amount1Desired, tickLower, tickUpper); (amount0, amount1) = pool03.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: msg.sender}))); shares = _calcShare(amount0, amount1); _mint(msg.sender, shares); require(totalSupply() <= maxTotalSupply, "MTS"); refundETH(); emit Deposit(msg.sender, shares, amount0, amount1); } /// @inheritdoc ISorbettoFragola function withdraw( uint256 shares ) external override nonReentrant checkDeviation updateVault(msg.sender) returns ( uint256 amount0, uint256 amount1 ) { require(shares > 0, "S"); (amount0, amount1) = pool03.burnLiquidityShare(tickLower, tickUpper, totalSupply(), shares, msg.sender); // Burn shares _burn(msg.sender, shares); emit Withdraw(msg.sender, shares, amount0, amount1); } /// @inheritdoc ISorbettoFragola function rerange() external override nonReentrant checkDeviation updateVault(address(0)) { //Burn all liquidity from pool to rerange for Sorbetto's balances. pool03.burnAllLiquidity(tickLower, tickUpper); // Emit snapshot to record balances uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); int24 baseThreshold = tickSpacing * ISorbettoStrategy(strategy).tickRangeMultiplier(); //Get exact ticks depending on Sorbetto's balances (tickLower, tickUpper) = pool03.getPositionTicks(balance0, balance1, baseThreshold, tickSpacing); //Get Liquidity for Sorbetto's balances uint128 liquidity = pool03.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool (uint256 amount0, uint256 amount1) = pool03.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, amount0, amount1); } /// @inheritdoc ISorbettoFragola function rebalance() external override onlyGovernance nonReentrant checkDeviation updateVault(address(0)) { //Burn all liquidity from pool to rerange for Sorbetto's balances. pool03.burnAllLiquidity(tickLower, tickUpper); //Calc base ticks (uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool03.slot0(); PoolVariables.Info memory cache = PoolVariables.Info(0, 0, 0, 0, 0, 0, 0); int24 baseThreshold = tickSpacing * ISorbettoStrategy(strategy).tickRangeMultiplier(); (cache.tickLower, cache.tickUpper) = PoolVariables.baseTicks(currentTick, baseThreshold, tickSpacing); cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); // Calc liquidity for base ticks cache.liquidity = pool03.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); // Get exact amounts for base ticks (cache.amount0, cache.amount1) = pool03.amountsForLiquidity(cache.liquidity, cache.tickLower, cache.tickUpper); // Get imbalanced token bool zeroForOne = PoolVariables.amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); // Calculate the amount of imbalanced token that should be swapped. Calculations strive to achieve one to one ratio int256 amountSpecified = zeroForOne ? int256(cache.amount0Desired.sub(cache.amount0).unsafeDiv(2)) : int256(cache.amount1Desired.sub(cache.amount1).unsafeDiv(2)); // always positive. "overflow" safe convertion cuz we are dividing by 2 // Calculate Price limit depending on price impact uint160 exactSqrtPriceImpact = sqrtPriceX96.mul160(ISorbettoStrategy(strategy).priceImpactPercentage() / 2) / 1e6; uint160 sqrtPriceLimitX96 = zeroForOne ? sqrtPriceX96.sub160(exactSqrtPriceImpact) : sqrtPriceX96.add160(exactSqrtPriceImpact); //Swap imbalanced token as long as we haven't used the entire amountSpecified and haven't reached the price limit pool03.swap( address(this), zeroForOne, amountSpecified, sqrtPriceLimitX96, abi.encode(SwapCallbackData({zeroForOne: zeroForOne})) ); (sqrtPriceX96, currentTick, , , , , ) = pool03.slot0(); // Emit snapshot to record balances cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); //Get exact ticks depending on Sorbetto's new balances (tickLower, tickUpper) = pool03.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing); cache.liquidity = pool03.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper); // Add liquidity to the pool (cache.amount0, cache.amount1) = pool03.mint( address(this), tickLower, tickUpper, cache.liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, cache.amount0, cache.amount1); } // Calcs user share depending on deposited amounts function _calcShare(uint256 amount0Desired, uint256 amount1Desired) internal view returns ( uint256 shares ) { shares = amount0Desired.mul(universalMultiplier).unsafeDiv(token1DecimalPower).add(amount1Desired.mul(1e12)); // Mul(1e12) Recalculated to match precisions } /// @dev Amount of token0 held as unused balance. function _balance0() internal view returns (uint256) { return IERC20(token0).balanceOf(address(this)); } /// @dev Amount of token1 held as unused balance. function _balance1() internal view returns (uint256) { return IERC20(token1).balanceOf(address(this)); } /// @dev collects fees from the pool function _earnFees() internal returns (uint256 userCollect0, uint256 userCollect1) { // Do zero-burns to poke the Uniswap pools so earned fees are updated pool03.burn(tickLower, tickUpper, 0); (uint256 collect0, uint256 collect1) = pool03.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); // Calculate protocol's and users share of fees uint256 feeToProtocol0 = collect0.mul(ISorbettoStrategy(strategy).protocolFee()).unsafeDiv(GLOBAL_DIVISIONER); uint256 feeToProtocol1 = collect1.mul(ISorbettoStrategy(strategy).protocolFee()).unsafeDiv(GLOBAL_DIVISIONER); accruedProtocolFees0 = accruedProtocolFees0.add(feeToProtocol0); accruedProtocolFees1 = accruedProtocolFees1.add(feeToProtocol1); userCollect0 = collect0.sub(feeToProtocol0); userCollect1 = collect1.sub(feeToProtocol1); usersFees0 = usersFees0.add(userCollect0); usersFees1 = usersFees1.add(userCollect1); emit CollectFees(collect0, collect1, usersFees0, usersFees1); } /// @notice Returns current Sorbetto's position in pool function position() external view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) { bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper); (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = pool03.positions(positionKey); } /// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay to the pool for the minted liquidity. /// @param amount0 The amount of token0 due to the pool for the minted liquidity /// @param amount1 The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external { require(msg.sender == address(pool03)); MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (amount0 > 0) pay(token0, decoded.payer, msg.sender, amount0); if (amount1 > 0) pay(token1, decoded.payer, msg.sender, amount1); } /// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap. /// @dev In the implementation you must pay to the pool for swap. /// @param amount0 The amount of token0 due to the pool for the swap /// @param amount1 The amount of token1 due to the pool for the swap /// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0, int256 amount1, bytes calldata _data ) external { require(msg.sender == address(pool03)); require(amount0 > 0 || amount1 > 0); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); bool zeroForOne = data.zeroForOne; if (zeroForOne) pay(token0, address(this), msg.sender, uint256(amount0)); else pay(token1, address(this), msg.sender, uint256(amount1)); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == weth && address(this).balance >= value) { // pay with WETH9 IWETH9(weth).deposit{value: value}(); // wrap only what is needed to pay IWETH9(weth).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } /** * @notice Used to withdraw accumulated protocol fees. */ function collectProtocolFees( uint256 amount0, uint256 amount1 ) external nonReentrant onlyGovernance updateVault(address(0)) { require(accruedProtocolFees0 >= amount0, "A0"); require(accruedProtocolFees1 >= amount1, "A1"); uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); if (balance0 >= amount0 && balance1 >= amount1) { if (amount0 > 0) pay(token0, address(this), msg.sender, amount0); if (amount1 > 0) pay(token1, address(this), msg.sender, amount1); } else { uint128 liquidity = pool03.liquidityForAmounts(amount0, amount1, tickLower, tickUpper); pool03.burnExactLiquidity(tickLower, tickUpper, liquidity, msg.sender); } accruedProtocolFees0 = accruedProtocolFees0.sub(amount0); accruedProtocolFees1 = accruedProtocolFees1.sub(amount1); emit RewardPaid(msg.sender, amount0, amount1); } /** * @notice Used to withdraw accumulated user's fees. */ function collectFees(uint256 amount0, uint256 amount1) external updateVault(msg.sender) { UserInfo storage user = userInfo[msg.sender]; require(user.token0Rewards >= amount0, "A0"); require(user.token1Rewards >= amount1, "A1"); uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); if (balance0 >= amount0 && balance1 >= amount1) { if (amount0 > 0) pay(token0, address(this), msg.sender, amount0); if (amount1 > 0) pay(token1, address(this), msg.sender, amount1); } else { uint128 liquidity = pool03.liquidityForAmounts(amount0, amount1, tickLower, tickUpper); (amount0, amount1) = pool03.burnExactLiquidity(tickLower, tickUpper, liquidity, msg.sender); } user.token0Rewards = user.token0Rewards.sub(amount0); user.token1Rewards = user.token1Rewards.sub(amount1); emit RewardPaid(msg.sender, amount0, amount1); } // Function modifier that calls update fees reward function modifier updateVault(address account) { _updateFeesReward(account); _; } // Function modifier that checks if price has not moved a lot recently. // This mitigates price manipulation during rebalance and also prevents placing orders // when it's too volatile. modifier checkDeviation() { pool03.checkDeviation(ISorbettoStrategy(strategy).maxTwapDeviation(), ISorbettoStrategy(strategy).twapDuration()); _; } modifier onlyPool() { require(msg.sender == address(pool03), "FP"); _; } // Updates user's fees reward function _updateFeesReward(address account) internal { uint liquidity = pool03.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero (uint256 collect0, uint256 collect1) = _earnFees(); token0PerShareStored = _tokenPerShare(collect0, token0PerShareStored); token1PerShareStored = _tokenPerShare(collect1, token1PerShareStored); if (account != address(0)) { UserInfo storage user = userInfo[msg.sender]; user.token0Rewards = _fee0Earned(account, token0PerShareStored); user.token0PerSharePaid = token0PerShareStored; user.token1Rewards = _fee1Earned(account, token1PerShareStored); user.token1PerSharePaid = token1PerShareStored; } } // Calculates how much token0 is entitled for a particular user function _fee0Earned(address account, uint256 fee0PerShare_) internal view returns (uint256) { UserInfo memory user = userInfo[account]; return balanceOf(account) .mul(fee0PerShare_.sub(user.token0PerSharePaid)) .unsafeDiv(1e18) .add(user.token0Rewards); } // Calculates how much token1 is entitled for a particular user function _fee1Earned(address account, uint256 fee1PerShare_) internal view returns (uint256) { UserInfo memory user = userInfo[account]; return balanceOf(account) .mul(fee1PerShare_.sub(user.token1PerSharePaid)) .unsafeDiv(1e18) .add(user.token1Rewards); } // Calculates how much token0 is provied per LP token function _tokenPerShare(uint256 collected, uint256 tokenPerShareStored) internal view returns (uint256) { uint _totalSupply = totalSupply(); if (_totalSupply > 0) { return tokenPerShareStored .add( collected .mul(1e18) .unsafeDiv(_totalSupply) ); } return tokenPerShareStored; } /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() internal { if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance); } /** * @notice `setGovernance()` should be called by the existing governance * address prior to calling this function. */ function setGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /** * @notice Governance address is not updated until the new governance * address has called `acceptGovernance()` to accept this responsibility. */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "PG"); governance = msg.sender; } // Sets maximum total supply of the PLP function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyGovernance { maxTotalSupply = _maxTotalSupply; } // Sets new strategy contract address for new settings function setStrategy(address _strategy) external onlyGovernance { require(_strategy != address(0), "NA"); strategy = _strategy; } }
@inheritdoc ISorbettoFragolaBurn all liquidity from pool to rerange for Sorbetto's balances.Calc base ticks Calc liquidity for base ticks Get exact amounts for base ticks Get imbalanced token Calculate the amount of imbalanced token that should be swapped. Calculations strive to achieve one to one ratio Calculate Price limit depending on price impactSwap imbalanced token as long as we haven't used the entire amountSpecified and haven't reached the price limit Emit snapshot to record balancesGet exact ticks depending on Sorbetto's new balances Add liquidity to the pool
function rebalance() external override onlyGovernance nonReentrant checkDeviation updateVault(address(0)) { pool03.burnAllLiquidity(tickLower, tickUpper); (uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool03.slot0(); PoolVariables.Info memory cache = PoolVariables.Info(0, 0, 0, 0, 0, 0, 0); int24 baseThreshold = tickSpacing * ISorbettoStrategy(strategy).tickRangeMultiplier(); (cache.tickLower, cache.tickUpper) = PoolVariables.baseTicks(currentTick, baseThreshold, tickSpacing); cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); cache.liquidity = pool03.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); (cache.amount0, cache.amount1) = pool03.amountsForLiquidity(cache.liquidity, cache.tickLower, cache.tickUpper); bool zeroForOne = PoolVariables.amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); int256 amountSpecified = zeroForOne ? int256(cache.amount0Desired.sub(cache.amount0).unsafeDiv(2)) uint160 exactSqrtPriceImpact = sqrtPriceX96.mul160(ISorbettoStrategy(strategy).priceImpactPercentage() / 2) / 1e6; uint160 sqrtPriceLimitX96 = zeroForOne ? sqrtPriceX96.sub160(exactSqrtPriceImpact) : sqrtPriceX96.add160(exactSqrtPriceImpact); pool03.swap( address(this), zeroForOne, amountSpecified, sqrtPriceLimitX96, ); (sqrtPriceX96, currentTick, , , , , ) = pool03.slot0(); cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); (tickLower, tickUpper) = pool03.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing); cache.liquidity = pool03.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper); (cache.amount0, cache.amount1) = pool03.mint( address(this), tickLower, tickUpper, cache.liquidity, emit Rerange(tickLower, tickUpper, cache.amount0, cache.amount1); }
13,977,446
pragma solidity 0.5.16; import "./FlashToken.sol"; import "https://github.com/erasureprotocol/erasure-protocol/blob/v1.2.0/contracts/modules/Spawner.sol"; contract UniswapFactoryInterface { // Public Variables address public exchangeTemplate; uint256 public tokenCount; // Create Exchange function createExchange(address token) external returns (address exchange); // Get Exchange and Token Info function getExchange(address token) external view returns (address exchange); function getToken(address exchange) external view returns (address token); function getTokenWithId(uint256 tokenId) external view returns (address token); // Never use function initializeFactory(address template) external; } /// @title FlashTokenFactory /// @author Stephane Gosselin (@thegostep) /// @notice An Erasure style factory for Wrapping FlashTokens contract FlashTokenFactory is Spawner { uint256 private _tokenCount; address private _templateContract; mapping(address => address) private _baseToFlash; mapping(address => address) private _flashToBase; mapping(uint256 => address) private _idToBase; event TemplateSet(address indexed templateContract); event FlashTokenCreated( address indexed token, address indexed flashToken, address indexed uniswapExchange, uint256 tokenID ); /// @notice Initialize factory with template contract. function setTemplate(address templateContract) public { require(_templateContract == address(0)); _templateContract = templateContract; emit TemplateSet(templateContract); } /// @notice Create a FlashToken wrap for any ERC20 token function createFlashToken(address token) public returns (address flashToken) { require(token != address(0), "cannot wrap address 0"); if (_baseToFlash[token] != address(0)) { return _baseToFlash[token]; } else { require(_baseToFlash[token] == address(0), "token already wrapped"); flashToken = _flashWrap(token); address uniswapExchange = UniswapFactoryInterface( 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95 ) .createExchange(flashToken); _baseToFlash[token] = flashToken; _flashToBase[flashToken] = token; _tokenCount += 1; _idToBase[_tokenCount] = token; emit FlashTokenCreated( token, flashToken, uniswapExchange, _tokenCount ); return flashToken; } } /// @notice Initialize instance function _flashWrap(address token) private returns (address flashToken) { FlashToken template; bytes memory initCalldata = abi.encodeWithSelector( template.initialize.selector, token ); return Spawner._spawn(address(this), _templateContract, initCalldata); } // Getters /// @notice Get FlashToken contract associated with given ERC20 token function getFlashToken(address token) public view returns (address flashToken) { return _baseToFlash[token]; } /// @notice Get ERC20 token contract associated with given FlashToken function getBaseToken(address flashToken) public view returns (address token) { return _flashToBase[flashToken]; } /// @notice Get ERC20 token contract associated with given FlashToken ID function getBaseFromID(uint256 tokenID) public view returns (address token) { return _idToBase[tokenID]; } /// @notice Get count of FlashToken contracts created from this factory function getTokenCount() public view returns (uint256 tokenCount) { return _tokenCount; } }
Create a FlashToken wrap for any ERC20 token
function createFlashToken(address token) public returns (address flashToken) { require(token != address(0), "cannot wrap address 0"); if (_baseToFlash[token] != address(0)) { return _baseToFlash[token]; require(_baseToFlash[token] == address(0), "token already wrapped"); flashToken = _flashWrap(token); address uniswapExchange = UniswapFactoryInterface( 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95 ) .createExchange(flashToken); _baseToFlash[token] = flashToken; _flashToBase[flashToken] = token; _tokenCount += 1; _idToBase[_tokenCount] = token; emit FlashTokenCreated( token, flashToken, uniswapExchange, _tokenCount ); return flashToken; } }
1,065,722
// Sources flattened with hardhat v2.8.3 https://hardhat.org // File @openzeppelin/contracts/utils/Context.sol@v4.4.2 // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/Ownable.sol@v4.4.2 // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.4.2 // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol@v4.4.2 // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/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 @openzeppelin/contracts/token/ERC20/ERC20.sol@v4.4.2 // OpenZeppelin Contracts v4.4.1 (token/ERC20/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 @openzeppelin/contracts/utils/math/SafeMath.sol@v4.4.2 // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol@v1.0.1 pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol@v1.0.1 pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol@v1.1.0-beta.0 pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol@v1.1.0-beta.0 pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File contracts/OZZY.sol pragma solidity ^0.8.0; /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } library SafeMathInt { function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns (uint256); /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed(address indexed from, uint256 weiAmount); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn(address indexed to, uint256 weiAmount); } /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns (uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns (uint256); } /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract DividendPayingToken is Context, Ownable, ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; address public rewardToken; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 internal constant magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; constructor(address _rewardToken, string memory _name, string memory _symbol) ERC20(_name, _symbol) { rewardToken = _rewardToken; } function distributeDividends(uint256 amount) public { require(totalSupply() > 0); uint256 balBefore = IERC20(rewardToken).balanceOf(address(this)); IERC20(rewardToken).transferFrom(_msgSender(), address(this), amount); uint256 received = (IERC20(rewardToken).balanceOf(address(this))).sub(balBefore); if (received > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (received).mul(magnitude) / totalSupply() ); emit DividendsDistributed(_msgSender(), received); totalDividendsDistributed = totalDividendsDistributed.add(received); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(_msgSender()); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add( _withdrawableDividend ); emit DividendWithdrawn(user, _withdrawableDividend); bool success = IERC20(rewardToken).transfer( user, _withdrawableDividend ); if (!success) { withdrawnDividends[user] = withdrawnDividends[user].sub( _withdrawableDividend ); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns (uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return (magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() + magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer(address from, address to, uint256 value) internal virtual override { int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from] + _magCorrection; magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to] - _magCorrection; } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] - (magnifiedDividendPerShare.mul(value)).toInt256Safe(); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] + (magnifiedDividendPerShare.mul(value)).toInt256Safe(); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } contract ERC20DividendToken is Context, ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; ERC20DividendTracker public dividendTracker; address public rewardToken; uint256 public minTokensBeforeSwap; uint256 public burnBuyFee; uint256 public liquidityBuyFee; uint256 public charityBuyFee; uint256 public rewardsBuyFee; uint256 public totalBuyFees; uint256 public burnSellFee; uint256 public liquiditySellFee; uint256 public communityFundSellFee; uint256 public rewardsSellFee; uint256 public totalSellFees; address public burnAddress; address public charityAddress; address public communityFundAddress; address public liquidityReceiver; uint256 public liquidityPending; uint256 public charityPending; uint256 public communityFundPending; // use by default 300,000 gas to process auto-claiming dividends uint256 public gasForProcessing = 300000; // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; uint256 public maxTxAmount; uint256 public maxWalletAmount; mapping (address => bool) public isExcludedFromLimits; event DeployedDividendTracker( address indexed newAddress ); event UpdateUniswapV2Router( address indexed newAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event GasForProcessingUpdated( uint256 indexed newValue, uint256 indexed oldValue ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SendDividends(uint256 tokensSwapped, uint256 amount); event SwapAndSendFeeToAddress(address indexed recipient, uint256 tokensSwapped, uint256 amount); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); constructor(string memory name_, string memory symbol_, uint256 totalSupply_, address routerV2_, address rewardToken_) ERC20(name_, symbol_) { setBuyFees(1, 2, 2, 5); setSellFees(1, 2, 2, 5); rewardToken = rewardToken_; minTokensBeforeSwap = 100_000 * (10**18); maxTxAmount = totalSupply_ * (10**16); // 1% maxWalletAmount = totalSupply_ * 2 * (10**16); // 2% _deployDividendTracker(routerV2_, rewardToken_); _updateUniswapV2Router(routerV2_); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromLimits(owner(), true); excludeFromLimits(address(this), true); excludeFromLimits(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), totalSupply_ * (10**18)); } receive() external payable {} function excludeFromLimits(address account, bool excluded) public onlyOwner { isExcludedFromLimits[account] = excluded; } function changeMaxTxAmount(uint256 amount) public onlyOwner { maxTxAmount = amount; } function changeMaxWalletAmount(uint256 amount) public onlyOwner { maxWalletAmount = amount; } function setMinTokensBeforeSwap(uint256 amount) external onlyOwner { minTokensBeforeSwap = amount; } function _deployDividendTracker(address _uniswapV2Router, address rewardToken_) internal { dividendTracker = new ERC20DividendTracker(rewardToken_); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(0xdead)); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); emit DeployedDividendTracker(address(dividendTracker)); } function _updateUniswapV2Router(address newAddress) internal { uniswapV2Router = IUniswapV2Router02(newAddress); address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); excludeFromLimits(newAddress, true); uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); emit UpdateUniswapV2Router(newAddress); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees( address[] calldata accounts, bool excluded ) public onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setBurnWallet(address wallet) public onlyOwner { burnAddress = wallet; } function setCharityWallet(address wallet) public onlyOwner { charityAddress = wallet; } function setCommunityFundWallet(address wallet) public onlyOwner { communityFundAddress = wallet; } function setLiquidityReceiver(address wallet) public onlyOwner { liquidityReceiver = wallet; } function setBuyFees(uint256 _burnBuyFee, uint256 _liquidityBuyFee, uint256 _charityBuyFee, uint256 _rewardsBuyFee) public onlyOwner { burnBuyFee = _burnBuyFee; liquidityBuyFee = _liquidityBuyFee; charityBuyFee = _charityBuyFee; rewardsBuyFee = _rewardsBuyFee; totalBuyFees = burnBuyFee.add(liquidityBuyFee).add(charityBuyFee).add(rewardsBuyFee); } function setSellFees(uint256 _burnSellFee, uint256 _liquiditySellFee, uint256 _communityFundSellFee, uint256 _rewardsSellFee) public onlyOwner { burnSellFee = _burnSellFee; liquiditySellFee = _liquiditySellFee; communityFundSellFee = _communityFundSellFee; rewardsSellFee = _rewardsSellFee; totalSellFees = burnSellFee.add(liquiditySellFee).add(communityFundSellFee).add(rewardsSellFee); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "ERC20DividendToken: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require( automatedMarketMakerPairs[pair] != value, "ERC20DividendToken: Automated market maker pair is already set to that value" ); automatedMarketMakerPairs[pair] = value; if (value) { excludeFromLimits(pair, true); dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function updateGasForProcessing(uint256 newValue) public onlyOwner { require( newValue >= 200000 && newValue <= 500000, "ERC20DividendToken: gasForProcessing must be between 200,000 and 500,000" ); require( newValue != gasForProcessing, "ERC20DividendToken: Cannot update gasForProcessing to same value" ); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getClaimWait() external view returns (uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns (uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function excludeFromDividends(address account) external onlyOwner { dividendTracker.excludeFromDividends(account); } function includeInDividends(address account) external onlyOwner { dividendTracker.includeInDividends(account, balanceOf(account)); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256 ) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256 ) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { ( uint256 iterations, uint256 claims, uint256 lastProcessedIndex ) = dividendTracker.process(gas); emit ProcessedDividendTracker( iterations, claims, lastProcessedIndex, false, gas, tx.origin ); } function claim() external { dividendTracker.processAccount(_msgSender(), false); } function getLastProcessedIndex() external view returns (uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() public view returns (uint256) { return dividendTracker.getNumberOfTokenHolders(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(balanceOf(from) >= amount, "ERC20: transfer amount exceeds balance"); if (!isExcludedFromLimits[from] || (automatedMarketMakerPairs[from] && !isExcludedFromLimits[to])) { require(amount <= maxTxAmount, "Anti-whale: Transfer amount exceeds max limit"); } if (!isExcludedFromLimits[to]) { require(balanceOf(to) + amount <= maxWalletAmount, "Anti-whale: Wallet amount exceeds max limit"); } if (amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= minTokensBeforeSwap; if ( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; if (charityPending > 0) { swapAndSendFeeToAddress(charityAddress, charityPending); charityPending = 0; } if (communityFundPending > 0) { swapAndSendFeeToAddress(communityFundAddress, communityFundPending); communityFundPending = 0; } if (liquidityPending > 0) { swapAndLiquify(liquidityPending); liquidityPending = 0; } if (balanceOf(address(this)) > 0) swapAndSendDividends(balanceOf(address(this))); swapping = false; } bool takeFee = !swapping && (automatedMarketMakerPairs[from] || automatedMarketMakerPairs[to]); // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if (automatedMarketMakerPairs[from]) { // BUY fees = amount.mul(totalBuyFees).div(100); amount = amount.sub(fees); liquidityPending += fees.mul(liquidityBuyFee).div(totalBuyFees); charityPending += fees.mul(charityBuyFee).div(totalBuyFees); if (burnBuyFee > 0) { uint256 burnTokens = fees.mul(burnBuyFee).div(totalBuyFees); fees = fees.sub(burnTokens); super._transfer(from, burnAddress, burnTokens); } } else { // SELL fees = amount.mul(totalSellFees).div(100); amount = amount.sub(fees); liquidityPending += fees.mul(liquiditySellFee).div(totalSellFees); communityFundPending += fees.mul(communityFundSellFee).div(totalSellFees); if (burnSellFee > 0) { uint256 burnTokens = fees.mul(burnSellFee).div(totalSellFees); fees = fees.sub(burnTokens); super._transfer(from, burnAddress, burnTokens); } } if (fees > 0) { super._transfer(from, address(this), fees); } } super._transfer(from, to, amount); try dividendTracker.setBalance(from, balanceOf(from)) {} catch {} try dividendTracker.setBalance(to, balanceOf(to)) {} catch {} if (!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns ( uint256 iterations, uint256 claims, uint256 lastProcessedIndex ) { emit ProcessedDividendTracker( iterations, claims, lastProcessedIndex, true, gas, tx.origin ); } catch {} } } function swapAndLiquify(uint256 tokens) private { // split the contract balance into halves uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function swapTokensForERC20(uint256 tokenAmount) private { address[] memory path = new address[](3); path[0] = address(this); path[1] = uniswapV2Router.WETH(); path[2] = rewardToken; _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityReceiver, block.timestamp ); } function swapAndSendDividends(uint256 tokens) private { swapTokensForERC20(tokens); uint256 dividends = IERC20(rewardToken).balanceOf(address(this)); bool success = IERC20(rewardToken).approve(address(dividendTracker), dividends); if (getNumberOfDividendTokenHolders() > 0 && success) { dividendTracker.distributeDividends(dividends); emit SendDividends(tokens, dividends); } } function swapAndSendFeeToAddress(address recipient, uint256 tokens) private { uint256 initialBalance = IERC20(rewardToken).balanceOf(address(this)); swapTokensForERC20(tokens); uint256 dividends = (IERC20(rewardToken).balanceOf(address(this))).sub(initialBalance); bool success = IERC20(rewardToken).transfer(recipient, dividends); if(success) { emit SwapAndSendFeeToAddress(recipient, tokens, dividends); } } } contract ERC20DividendTracker is Ownable, DividendPayingToken { using SafeMath for uint256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping(address => bool) public isExcludedFromDividends; mapping(address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public minimumTokenBalanceForDividends; event ExcludeFromDividends(address indexed account); event IncludeInDividends(address indexed account); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim( address indexed account, uint256 amount, bool indexed automatic ); constructor(address rewardToken_) DividendPayingToken(rewardToken_, "Dividend_Tracker", "Dividend_Tracker") { claimWait = 60 minutes; minimumTokenBalanceForDividends = 100 * (10**18); } function _transfer( address, address, uint256 ) internal pure override { require(false, "Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require( false, "Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main ERC20DividendToken contract." ); } function excludeFromDividends(address account) external onlyOwner { require(!isExcludedFromDividends[account]); isExcludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function includeInDividends(address account, uint256 balance) external onlyOwner { require(isExcludedFromDividends[account]); isExcludedFromDividends[account] = false; _setBalance(account, balance); tokenHoldersMap.set(account, balance); emit IncludeInDividends(account); } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require( newClaimWait >= 1 && newClaimWait <= 86400, "Dividend_Tracker: claimWait must be updated to between 1 second and 24 hours" ); require( newClaimWait != claimWait, "Dividend_Tracker: Cannot update claimWait to same value" ); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns (uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns (uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable ) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if (index >= 0) { if (uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index - int256(lastProcessedIndex); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index + int256(processesUntilEndOfArray); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256 ) { if (index >= tokenHoldersMap.size()) { return (address(0), -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if (lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address account, uint256 newBalance) external onlyOwner { if (isExcludedFromDividends[account]) { return; } if (newBalance >= minimumTokenBalanceForDividends) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public returns ( uint256, uint256, uint256 ) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if (numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if (canAutoClaim(lastClaimTimes[account])) { if (processAccount(account, true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(payable(account)); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } } contract OZZY is ERC20DividendToken { uint256 private _tokenSupply = 1_000_000_000; /** * @dev Choose proper router address according to your network: * Ethereum mainnet: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D (Uniswap) * BSC mainnet: 0x10ED43C718714eb63d5aA57B78B54704E256024E (PancakeSwap) * BSC testnet: 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 * Polygon: 0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff * Fantom: 0xF491e7B69E4244ad4002BC14e878a34207E38c29 */ /** * @dev BUSD addresses: * BSC mainnet: 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56 * BSC testnet: 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7 */ address private _burnAddress = 0x6855FB893a4088637f86663197a3Af0F395970D3; address private _charityAddress = 0x4B71Db09946f8676ABa8002a1a4d67e98c463EBA; address private _communityFundAddress = 0x66C6F9e48A3E203A06Fc07bb8ac8676C75163Ae4; address private _liquidityReceiver = 0xbb3e6Da084C5C05427557Fa719EeF8eC65783d81; // address private _owner = 0x0e83e9a254450b14D75e4e47F2fa82211f0e2647; constructor (address _routerAddress, address _rewardToken) ERC20DividendToken("Faded & Famous", "OZZY", _tokenSupply, _routerAddress, _rewardToken) { setBurnWallet(_burnAddress); setCharityWallet(_charityAddress); setCommunityFundWallet(_communityFundAddress); setLiquidityReceiver(_liquidityReceiver); } }
Internal function that transfer tokens from one address to another. Update magnifiedDividendCorrections to keep dividends unchanged. from The address to transfer from. to The address to transfer to. value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override { int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from] + _magCorrection; magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to] - _magCorrection; }
6,286,416
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/RandomCollectorSelector.sol
VRF Callback Function/
function fulfillRandomWords(uint _requestId, uint[] memory _randomWords) internal override { require(s_requests[_requestId].paid > 0, "request not found"); _VRFResponseStatus = true; s_requests[_requestId].fulfilled = true; s_requests[_requestId].randomWords = _randomWords; _RandomResults.push(_randomWords[0]); emit RequestFulfilled(_requestId, _randomWords, s_requests[_requestId].paid); } modifier onlyAdmin
8,471,232
./full_match/1/0x959D3DdC42740F13A2de31Fb21642B0D332f7203/sources/HoldefiV1.1/Holdefi.sol
Update supply index of a market market Address of the given market
function updateSupplyIndex (address market) internal { (uint256 currentSupplyIndex, uint256 supplyRate) = getCurrentSupplyIndex(market); marketAssets[market].supplyIndex = currentSupplyIndex; marketAssets[market].supplyIndexUpdateTime = block.timestamp; emit UpdateSupplyIndex(market, currentSupplyIndex, supplyRate); }
4,911,666
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "./PrizePoolBuilder.sol"; import "../registry/RegistryInterface.sol"; import "../prize-pool/compound/CompoundPrizePoolProxyFactory.sol"; import "../external/compound/CTokenInterface.sol"; /// @title Creates new Compound Prize Pools /* solium-disable security/no-block-members */ contract CompoundPrizePoolBuilder is PrizePoolBuilder { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; /// @notice The configuration used to initialize the Compound Prize Pool struct CompoundPrizePoolConfig { CTokenInterface cToken; uint256 maxExitFeeMantissa; uint256 maxTimelockDuration; } RegistryInterface public reserveRegistry; CompoundPrizePoolProxyFactory public compoundPrizePoolProxyFactory; constructor ( RegistryInterface _reserveRegistry, CompoundPrizePoolProxyFactory _compoundPrizePoolProxyFactory ) public { require(address(_reserveRegistry) != address(0), "CompoundPrizePoolBuilder/reserveRegistry-not-zero"); require(address(_compoundPrizePoolProxyFactory) != address(0), "CompoundPrizePoolBuilder/compound-prize-pool-builder-not-zero"); reserveRegistry = _reserveRegistry; compoundPrizePoolProxyFactory = _compoundPrizePoolProxyFactory; } /// @notice Creates a new Compound Prize Pool with a preconfigured prize strategy. /// @param config The config to use to initialize the Compound Prize Pool /// @return The Compound Prize Pool function createCompoundPrizePool( CompoundPrizePoolConfig calldata config ) external returns (CompoundPrizePool) { CompoundPrizePool prizePool = compoundPrizePoolProxyFactory.create(); ControlledTokenInterface[] memory tokens; prizePool.initialize( reserveRegistry, tokens, config.maxExitFeeMantissa, config.maxTimelockDuration, config.cToken ); prizePool.transferOwnership(msg.sender); emit PrizePoolCreated(msg.sender, address(prizePool)); return prizePool; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../prize-pool/PrizePool.sol"; import "../prize-strategy/PeriodicPrizeStrategy.sol"; contract PrizePoolBuilder { using SafeCastUpgradeable for uint256; event PrizePoolCreated ( address indexed creator, address indexed prizePool ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../registry/RegistryInterface.sol"; import "../reserve/ReserveInterface.sol"; import "./YieldSource.sol"; import "../token/TokenListenerInterface.sol"; import "../token/TokenListenerLibrary.sol"; import "../token/ControlledToken.sol"; import "../token/TokenControllerInterface.sol"; import "../utils/MappedSinglyLinkedList.sol"; import "./PrizePoolInterface.sol"; /// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool. /// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract. /// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens abstract contract PrizePool is PrizePoolInterface, YieldSource, OwnableUpgradeable, ReentrancyGuardUpgradeable, TokenControllerInterface { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using ERC165CheckerUpgradeable for address; /// @dev Emitted when an instance is initialized event Initialized( address reserveRegistry, uint256 maxExitFeeMantissa, uint256 maxTimelockDuration ); /// @dev Event emitted when controlled token is added event ControlledTokenAdded( ControlledTokenInterface indexed token ); /// @dev Emitted when reserve is captured. event ReserveFeeCaptured( uint256 amount ); event AwardCaptured( uint256 amount ); /// @dev Event emitted when assets are deposited event Deposited( address indexed operator, address indexed to, address indexed token, uint256 amount, address referrer ); /// @dev Event emitted when timelocked funds are re-deposited event TimelockDeposited( address indexed operator, address indexed to, address indexed token, uint256 amount ); /// @dev Event emitted when interest is awarded to a winner event Awarded( address indexed winner, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC20s are awarded to a winner event AwardedExternalERC20( address indexed winner, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC20s are transferred out event TransferredExternalERC20( address indexed to, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC721s are awarded to a winner event AwardedExternalERC721( address indexed winner, address indexed token, uint256[] tokenIds ); /// @dev Event emitted when assets are withdrawn instantly event InstantWithdrawal( address indexed operator, address indexed from, address indexed token, uint256 amount, uint256 redeemed, uint256 exitFee ); /// @dev Event emitted upon a withdrawal with timelock event TimelockedWithdrawal( address indexed operator, address indexed from, address indexed token, uint256 amount, uint256 unlockTimestamp ); event ReserveWithdrawal( address indexed to, uint256 amount ); /// @dev Event emitted when timelocked funds are swept back to a user event TimelockedWithdrawalSwept( address indexed operator, address indexed from, uint256 amount, uint256 redeemed ); /// @dev Event emitted when the Liquidity Cap is set event LiquidityCapSet( uint256 liquidityCap ); /// @dev Event emitted when the Credit plan is set event CreditPlanSet( address token, uint128 creditLimitMantissa, uint128 creditRateMantissa ); /// @dev Event emitted when the Prize Strategy is set event PrizeStrategySet( address indexed prizeStrategy ); /// @dev Emitted when credit is minted event CreditMinted( address indexed user, address indexed token, uint256 amount ); /// @dev Emitted when credit is burned event CreditBurned( address indexed user, address indexed token, uint256 amount ); struct CreditPlan { uint128 creditLimitMantissa; uint128 creditRateMantissa; } struct CreditBalance { uint192 balance; uint32 timestamp; bool initialized; } /// @dev Reserve to which reserve fees are sent RegistryInterface public reserveRegistry; /// @dev A linked list of all the controlled tokens MappedSinglyLinkedList.Mapping internal _tokens; /// @dev The Prize Strategy that this Prize Pool is bound to. TokenListenerInterface public prizeStrategy; /// @dev The maximum possible exit fee fraction as a fixed point 18 number. /// For example, if the maxExitFeeMantissa is "0.1 ether", then the maximum exit fee for a withdrawal of 100 Dai will be 10 Dai uint256 public maxExitFeeMantissa; /// @dev The maximum possible timelock duration for a timelocked withdrawal (in seconds). uint256 public maxTimelockDuration; /// @dev The total funds that are timelocked. uint256 public timelockTotalSupply; /// @dev The total funds that have been allocated to the reserve uint256 public reserveTotalSupply; /// @dev The total amount of funds that the prize pool can hold. uint256 public liquidityCap; /// @dev the The awardable balance uint256 internal _currentAwardBalance; /// @dev The timelocked balances for each user mapping(address => uint256) internal _timelockBalances; /// @dev The unlock timestamps for each user mapping(address => uint256) internal _unlockTimestamps; /// @dev Stores the credit plan for each token. mapping(address => CreditPlan) internal _tokenCreditPlans; /// @dev Stores each users balance of credit per token. mapping(address => mapping(address => CreditBalance)) internal _tokenCreditBalances; /// @notice Initializes the Prize Pool /// @param _controlledTokens Array of ControlledTokens that are controlled by this Prize Pool. /// @param _maxExitFeeMantissa The maximum exit fee size /// @param _maxTimelockDuration The maximum length of time the withdraw timelock function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration ) public initializer { require(address(_reserveRegistry) != address(0), "PrizePool/reserveRegistry-not-zero"); _tokens.initialize(); for (uint256 i = 0; i < _controlledTokens.length; i++) { _addControlledToken(_controlledTokens[i]); } __Ownable_init(); __ReentrancyGuard_init(); _setLiquidityCap(uint256(-1)); reserveRegistry = _reserveRegistry; maxExitFeeMantissa = _maxExitFeeMantissa; maxTimelockDuration = _maxTimelockDuration; emit Initialized( address(_reserveRegistry), maxExitFeeMantissa, maxTimelockDuration ); } /// @dev Returns the address of the underlying ERC20 asset /// @return The address of the asset function token() external override view returns (address) { return address(_token()); } /// @dev Returns the total underlying balance of all assets. This includes both principal and interest. /// @return The underlying balance of assets function balance() external returns (uint256) { return _balance(); } /// @dev Checks with the Prize Pool if a specific token type may be awarded as an external prize /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function canAwardExternal(address _externalToken) external view returns (bool) { return _canAwardExternal(_externalToken); } /// @notice Deposits timelocked tokens for a user back into the Prize Pool as another asset. /// @param to The address receiving the tokens /// @param amount The amount of timelocked assets to re-deposit /// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship) function timelockDepositTo( address to, uint256 amount, address controlledToken ) external onlyControlledToken(controlledToken) canAddLiquidity(amount) nonReentrant { address operator = _msgSender(); _mint(to, amount, controlledToken, address(0)); _timelockBalances[operator] = _timelockBalances[operator].sub(amount); timelockTotalSupply = timelockTotalSupply.sub(amount); emit TimelockDeposited(operator, to, controlledToken, amount); } /// @notice Deposit assets into the Prize Pool in exchange for tokens /// @param to The address receiving the newly minted tokens /// @param amount The amount of assets to deposit /// @param controlledToken The address of the type of token the user is minting /// @param referrer The referrer of the deposit function depositTo( address to, uint256 amount, address controlledToken, address referrer ) external override onlyControlledToken(controlledToken) canAddLiquidity(amount) nonReentrant { address operator = _msgSender(); _mint(to, amount, controlledToken, referrer); _token().safeTransferFrom(operator, address(this), amount); _supply(amount); emit Deposited(operator, to, controlledToken, amount, referrer); } /// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit. /// @param from The address to redeem tokens from. /// @param amount The amount of tokens to redeem for assets. /// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship) /// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn. /// @return The actual exit fee paid function withdrawInstantlyFrom( address from, uint256 amount, address controlledToken, uint256 maximumExitFee ) external override nonReentrant onlyControlledToken(controlledToken) returns (uint256) { (uint256 exitFee, uint256 burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); require(exitFee <= maximumExitFee, "PrizePool/exit-fee-exceeds-user-maximum"); // burn the credit _burnCredit(from, controlledToken, burnedCredit); // burn the tickets ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount); // redeem the tickets less the fee uint256 amountLessFee = amount.sub(exitFee); uint256 redeemed = _redeem(amountLessFee); _token().safeTransfer(from, redeemed); emit InstantWithdrawal(_msgSender(), from, controlledToken, amount, redeemed, exitFee); return exitFee; } /// @notice Limits the exit fee to the maximum as hard-coded into the contract /// @param withdrawalAmount The amount that is attempting to be withdrawn /// @param exitFee The exit fee to check against the limit /// @return The passed exit fee if it is less than the maximum, otherwise the maximum fee is returned. function _limitExitFee(uint256 withdrawalAmount, uint256 exitFee) internal view returns (uint256) { uint256 maxFee = FixedPoint.multiplyUintByMantissa(withdrawalAmount, maxExitFeeMantissa); if (exitFee > maxFee) { exitFee = maxFee; } return exitFee; } /// @notice Withdraw assets from the Prize Pool by placing them into the timelock. /// The timelock is used to ensure that the tickets have contributed their fair share of the prize. /// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them. /// If the existing timelocked funds are still locked, then the incoming /// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one. /// @param from The address to withdraw from /// @param amount The amount to withdraw /// @param controlledToken The type of token being withdrawn /// @return The timestamp from which the funds can be swept function withdrawWithTimelockFrom( address from, uint256 amount, address controlledToken ) external override nonReentrant onlyControlledToken(controlledToken) returns (uint256) { uint256 blockTime = _currentTime(); (uint256 lockDuration, uint256 burnedCredit) = _calculateTimelockDuration(from, controlledToken, amount); uint256 unlockTimestamp = blockTime.add(lockDuration); _burnCredit(from, controlledToken, burnedCredit); ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount); _mintTimelock(from, amount, unlockTimestamp); emit TimelockedWithdrawal(_msgSender(), from, controlledToken, amount, unlockTimestamp); // return the block at which the funds will be available return unlockTimestamp; } /// @notice Adds to a user's timelock balance. It will attempt to sweep before updating the balance. /// Note that this will overwrite the previous unlock timestamp. /// @param user The user whose timelock balance should increase /// @param amount The amount to increase by /// @param timestamp The new unlock timestamp function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal { // Sweep the old balance, if any address[] memory users = new address[](1); users[0] = user; _sweepTimelockBalances(users); timelockTotalSupply = timelockTotalSupply.add(amount); _timelockBalances[user] = _timelockBalances[user].add(amount); _unlockTimestamps[user] = timestamp; // if the funds should already be unlocked if (timestamp <= _currentTime()) { _sweepTimelockBalances(users); } } /// @notice Updates the Prize Strategy when tokens are transferred between holders. /// @param from The address the tokens are being transferred from (0 if minting) /// @param to The address the tokens are being transferred to (0 if burning) /// @param amount The amount of tokens being trasferred function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) { if (from != address(0)) { uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from); // first accrue credit for their old balance uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0); if (from != to) { // if they are sending funds to someone else, we need to limit their accrued credit to their new balance newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance); } _updateCreditBalance(from, msg.sender, newCreditBalance); } if (to != address(0) && to != from) { _accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0); } // if we aren't minting if (from != address(0) && address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender); } } /// @notice Returns the balance that is available to award. /// @dev captureAwardBalance() should be called first /// @return The total amount of assets to be awarded for the current prize function awardBalance() external override view returns (uint256) { return _currentAwardBalance; } /// @notice Captures any available interest as award balance. /// @dev This function also captures the reserve fees. /// @return The total amount of assets to be awarded for the current prize function captureAwardBalance() external override nonReentrant returns (uint256) { uint256 tokenTotalSupply = _tokenTotalSupply(); // it's possible for the balance to be slightly less due to rounding errors in the underlying yield source uint256 currentBalance = _balance(); uint256 totalInterest = (currentBalance > tokenTotalSupply) ? currentBalance.sub(tokenTotalSupply) : 0; uint256 unaccountedPrizeBalance = (totalInterest > _currentAwardBalance) ? totalInterest.sub(_currentAwardBalance) : 0; if (unaccountedPrizeBalance > 0) { uint256 reserveFee = calculateReserveFee(unaccountedPrizeBalance); if (reserveFee > 0) { reserveTotalSupply = reserveTotalSupply.add(reserveFee); unaccountedPrizeBalance = unaccountedPrizeBalance.sub(reserveFee); emit ReserveFeeCaptured(reserveFee); } _currentAwardBalance = _currentAwardBalance.add(unaccountedPrizeBalance); emit AwardCaptured(unaccountedPrizeBalance); } return _currentAwardBalance; } function withdrawReserve(address to) external override onlyReserve returns (uint256) { uint256 amount = reserveTotalSupply; reserveTotalSupply = 0; uint256 redeemed = _redeem(amount); _token().safeTransfer(address(to), redeemed); emit ReserveWithdrawal(to, amount); return redeemed; } /// @notice Called by the prize strategy to award prizes. /// @dev The amount awarded must be less than the awardBalance() /// @param to The address of the winner that receives the award /// @param amount The amount of assets to be awarded /// @param controlledToken The address of the asset token being awarded function award( address to, uint256 amount, address controlledToken ) external override onlyPrizeStrategy onlyControlledToken(controlledToken) { if (amount == 0) { return; } require(amount <= _currentAwardBalance, "PrizePool/award-exceeds-avail"); _currentAwardBalance = _currentAwardBalance.sub(amount); _mint(to, amount, controlledToken, address(0)); uint256 extraCredit = _calculateEarlyExitFeeNoCredit(controlledToken, amount); _accrueCredit(to, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(to), extraCredit); emit Awarded(to, controlledToken, amount); } /// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything. /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function transferExternalERC20( address to, address externalToken, uint256 amount ) external override onlyPrizeStrategy { if (_transferOut(to, externalToken, amount)) { emit TransferredExternalERC20(to, externalToken, amount); } } /// @notice Called by the Prize-Strategy to award external ERC20 prizes /// @dev Used to award any arbitrary tokens held by the Prize Pool /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function awardExternalERC20( address to, address externalToken, uint256 amount ) external override onlyPrizeStrategy { if (_transferOut(to, externalToken, amount)) { emit AwardedExternalERC20(to, externalToken, amount); } } function _transferOut( address to, address externalToken, uint256 amount ) internal returns (bool) { require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token"); if (amount == 0) { return false; } IERC20Upgradeable(externalToken).safeTransfer(to, amount); return true; } /// @notice Called to mint controlled tokens. Ensures that token listener callbacks are fired. /// @param to The user who is receiving the tokens /// @param amount The amount of tokens they are receiving /// @param controlledToken The token that is going to be minted /// @param referrer The user who referred the minting function _mint(address to, uint256 amount, address controlledToken, address referrer) internal { if (address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenMint(to, amount, controlledToken, referrer); } ControlledToken(controlledToken).controllerMint(to, amount); } /// @notice Called by the prize strategy to award external ERC721 prizes /// @dev Used to award any arbitrary NFTs held by the Prize Pool /// @param to The address of the winner that receives the award /// @param externalToken The address of the external NFT token being awarded /// @param tokenIds An array of NFT Token IDs to be transferred function awardExternalERC721( address to, address externalToken, uint256[] calldata tokenIds ) external override onlyPrizeStrategy { require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token"); if (tokenIds.length == 0) { return; } for (uint256 i = 0; i < tokenIds.length; i++) { IERC721Upgradeable(externalToken).transferFrom(address(this), to, tokenIds[i]); } emit AwardedExternalERC721(to, externalToken, tokenIds); } /// @notice Calculates the reserve portion of the given amount of funds. If there is no reserve address, the portion will be zero. /// @param amount The prize amount /// @return The size of the reserve portion of the prize function calculateReserveFee(uint256 amount) public view returns (uint256) { ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup()); if (address(reserve) == address(0)) { return 0; } uint256 reserveRateMantissa = reserve.reserveRateMantissa(address(this)); if (reserveRateMantissa == 0) { return 0; } return FixedPoint.multiplyUintByMantissa(amount, reserveRateMantissa); } /// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts /// @param users An array of account addresses to sweep balances for /// @return The total amount of assets swept from the Prize Pool function sweepTimelockBalances( address[] calldata users ) external override nonReentrant returns (uint256) { return _sweepTimelockBalances(users); } /// @notice Sweep available timelocked balances to their owners. The full balances will be swept to the owners. /// @param users An array of owner addresses /// @return The total amount of assets swept from the Prize Pool function _sweepTimelockBalances( address[] memory users ) internal returns (uint256) { address operator = _msgSender(); uint256[] memory balances = new uint256[](users.length); uint256 totalWithdrawal; uint256 i; for (i = 0; i < users.length; i++) { address user = users[i]; if (_unlockTimestamps[user] <= _currentTime()) { totalWithdrawal = totalWithdrawal.add(_timelockBalances[user]); balances[i] = _timelockBalances[user]; delete _timelockBalances[user]; } } // if there is nothing to do, just quit if (totalWithdrawal == 0) { return 0; } timelockTotalSupply = timelockTotalSupply.sub(totalWithdrawal); uint256 redeemed = _redeem(totalWithdrawal); IERC20Upgradeable underlyingToken = IERC20Upgradeable(_token()); for (i = 0; i < users.length; i++) { if (balances[i] > 0) { delete _unlockTimestamps[users[i]]; uint256 shareMantissa = FixedPoint.calculateMantissa(balances[i], totalWithdrawal); uint256 transferAmount = FixedPoint.multiplyUintByMantissa(redeemed, shareMantissa); underlyingToken.safeTransfer(users[i], transferAmount); emit TimelockedWithdrawalSwept(operator, users[i], balances[i], transferAmount); } } return totalWithdrawal; } /// @notice Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds function calculateTimelockDuration( address from, address controlledToken, uint256 amount ) external override returns ( uint256 durationSeconds, uint256 burnedCredit ) { return _calculateTimelockDuration(from, controlledToken, amount); } /// @dev Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds /// @return burnedCredit The credit that was burned function _calculateTimelockDuration( address from, address controlledToken, uint256 amount ) internal returns ( uint256 durationSeconds, uint256 burnedCredit ) { (uint256 exitFee, uint256 _burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); uint256 duration = _estimateCreditAccrualTime(controlledToken, amount, exitFee); if (duration > maxTimelockDuration) { duration = maxTimelockDuration; } return (duration, _burnedCredit); } /// @notice Calculates the early exit fee for the given amount /// @param from The user who is withdrawing /// @param controlledToken The type of collateral being withdrawn /// @param amount The amount of collateral to be withdrawn /// @return exitFee The exit fee /// @return burnedCredit The user's credit that was burned function calculateEarlyExitFee( address from, address controlledToken, uint256 amount ) external override returns ( uint256 exitFee, uint256 burnedCredit ) { return _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); } /// @dev Calculates the early exit fee for the given amount /// @param amount The amount of collateral to be withdrawn /// @return Exit fee function _calculateEarlyExitFeeNoCredit(address controlledToken, uint256 amount) internal view returns (uint256) { return _limitExitFee( amount, FixedPoint.multiplyUintByMantissa(amount, _tokenCreditPlans[controlledToken].creditLimitMantissa) ); } /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit. /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) external override view returns (uint256 durationSeconds) { return _estimateCreditAccrualTime( _controlledToken, _principal, _interest ); } /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function _estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) internal view returns (uint256 durationSeconds) { // interest = credit rate * principal * time // => time = interest / (credit rate * principal) uint256 accruedPerSecond = FixedPoint.multiplyUintByMantissa(_principal, _tokenCreditPlans[_controlledToken].creditRateMantissa); if (accruedPerSecond == 0) { return 0; } return _interest.div(accruedPerSecond); } /// @notice Burns a users credit. /// @param user The user whose credit should be burned /// @param credit The amount of credit to burn function _burnCredit(address user, address controlledToken, uint256 credit) internal { _tokenCreditBalances[controlledToken][user].balance = uint256(_tokenCreditBalances[controlledToken][user].balance).sub(credit).toUint128(); emit CreditBurned(user, controlledToken, credit); } /// @notice Accrues ticket credit for a user assuming their current balance is the passed balance. May burn credit if they exceed their limit. /// @param user The user for whom to accrue credit /// @param controlledToken The controlled token whose balance we are checking /// @param controlledTokenBalance The balance to use for the user /// @param extra Additional credit to be added function _accrueCredit(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal { _updateCreditBalance( user, controlledToken, _calculateCreditBalance(user, controlledToken, controlledTokenBalance, extra) ); } function _calculateCreditBalance(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal view returns (uint256) { uint256 newBalance; CreditBalance storage creditBalance = _tokenCreditBalances[controlledToken][user]; if (!creditBalance.initialized) { newBalance = 0; } else { uint256 credit = _calculateAccruedCredit(user, controlledToken, controlledTokenBalance); newBalance = _applyCreditLimit(controlledToken, controlledTokenBalance, uint256(creditBalance.balance).add(credit).add(extra)); } return newBalance; } function _updateCreditBalance(address user, address controlledToken, uint256 newBalance) internal { uint256 oldBalance = _tokenCreditBalances[controlledToken][user].balance; _tokenCreditBalances[controlledToken][user] = CreditBalance({ balance: newBalance.toUint128(), timestamp: _currentTime().toUint32(), initialized: true }); if (oldBalance < newBalance) { emit CreditMinted(user, controlledToken, newBalance.sub(oldBalance)); } else { emit CreditBurned(user, controlledToken, oldBalance.sub(newBalance)); } } /// @notice Applies the credit limit to a credit balance. The balance cannot exceed the credit limit. /// @param controlledToken The controlled token that the user holds /// @param controlledTokenBalance The users ticket balance (used to calculate credit limit) /// @param creditBalance The new credit balance to be checked /// @return The users new credit balance. Will not exceed the credit limit. function _applyCreditLimit(address controlledToken, uint256 controlledTokenBalance, uint256 creditBalance) internal view returns (uint256) { uint256 creditLimit = FixedPoint.multiplyUintByMantissa( controlledTokenBalance, _tokenCreditPlans[controlledToken].creditLimitMantissa ); if (creditBalance > creditLimit) { creditBalance = creditLimit; } return creditBalance; } /// @notice Calculates the accrued interest for a user /// @param user The user whose credit should be calculated. /// @param controlledToken The controlled token that the user holds /// @param controlledTokenBalance The user's current balance of the controlled tokens. /// @return The credit that has accrued since the last credit update. function _calculateAccruedCredit(address user, address controlledToken, uint256 controlledTokenBalance) internal view returns (uint256) { uint256 userTimestamp = _tokenCreditBalances[controlledToken][user].timestamp; if (!_tokenCreditBalances[controlledToken][user].initialized) { return 0; } uint256 deltaTime = _currentTime().sub(userTimestamp); uint256 creditPerSecond = FixedPoint.multiplyUintByMantissa(controlledTokenBalance, _tokenCreditPlans[controlledToken].creditRateMantissa); return deltaTime.mul(creditPerSecond); } /// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit. /// @param user The user whose credit balance should be returned /// @return The balance of the users credit function balanceOfCredit(address user, address controlledToken) external override onlyControlledToken(controlledToken) returns (uint256) { _accrueCredit(user, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(user), 0); return _tokenCreditBalances[controlledToken][user].balance; } /// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether). /// @param _controlledToken The controlled token for whom to set the credit plan /// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether). /// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether). function setCreditPlanOf( address _controlledToken, uint128 _creditRateMantissa, uint128 _creditLimitMantissa ) external override onlyControlledToken(_controlledToken) onlyOwner { _tokenCreditPlans[_controlledToken] = CreditPlan({ creditLimitMantissa: _creditLimitMantissa, creditRateMantissa: _creditRateMantissa }); emit CreditPlanSet(_controlledToken, _creditLimitMantissa, _creditRateMantissa); } /// @notice Returns the credit rate of a controlled token /// @param controlledToken The controlled token to retrieve the credit rates for /// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee. /// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second. function creditPlanOf( address controlledToken ) external override view returns ( uint128 creditLimitMantissa, uint128 creditRateMantissa ) { creditLimitMantissa = _tokenCreditPlans[controlledToken].creditLimitMantissa; creditRateMantissa = _tokenCreditPlans[controlledToken].creditRateMantissa; } /// @notice Calculate the early exit for a user given a withdrawal amount. The user's credit is taken into account. /// @param from The user who is withdrawing /// @param controlledToken The token they are withdrawing /// @param amount The amount of funds they are withdrawing /// @return earlyExitFee The additional exit fee that should be charged. /// @return creditBurned The amount of credit that will be burned function _calculateEarlyExitFeeLessBurnedCredit( address from, address controlledToken, uint256 amount ) internal returns ( uint256 earlyExitFee, uint256 creditBurned ) { uint256 controlledTokenBalance = IERC20Upgradeable(controlledToken).balanceOf(from); require(controlledTokenBalance >= amount, "PrizePool/insuff-funds"); _accrueCredit(from, controlledToken, controlledTokenBalance, 0); /* The credit is used *last*. Always charge the fees up-front. How to calculate: Calculate their remaining exit fee. I.e. full exit fee of their balance less their credit. If the exit fee on their withdrawal is greater than the remaining exit fee, then they'll have to pay the difference. */ // Determine available usable credit based on withdraw amount uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount)); uint256 availableCredit; if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) { availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee); } // Determine amount of credit to burn and amount of fees required uint256 totalExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, amount); creditBurned = (availableCredit > totalExitFee) ? totalExitFee : availableCredit; earlyExitFee = totalExitFee.sub(creditBurned); return (earlyExitFee, creditBurned); } /// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold /// @param _liquidityCap The new liquidity cap for the prize pool function setLiquidityCap(uint256 _liquidityCap) external override onlyOwner { _setLiquidityCap(_liquidityCap); } function _setLiquidityCap(uint256 _liquidityCap) internal { liquidityCap = _liquidityCap; emit LiquidityCapSet(_liquidityCap); } /// @notice Allows the Governor to add Controlled Tokens to the Prize Pool /// @param _controlledToken The address of the Controlled Token to add function addControlledToken(ControlledTokenInterface _controlledToken) external override onlyOwner { _addControlledToken(_controlledToken); } /// @notice Adds a new controlled token /// @param _controlledToken The controlled token to add. Cannot be a duplicate. function _addControlledToken(ControlledTokenInterface _controlledToken) internal { require(_controlledToken.controller() == this, "PrizePool/token-ctrlr-mismatch"); _tokens.addAddress(address(_controlledToken)); emit ControlledTokenAdded(_controlledToken); } /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external override onlyOwner { _setPrizeStrategy(_prizeStrategy); } /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy function _setPrizeStrategy(TokenListenerInterface _prizeStrategy) internal { require(address(_prizeStrategy) != address(0), "PrizePool/prizeStrategy-not-zero"); require(address(_prizeStrategy).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PrizePool/prizeStrategy-invalid"); prizeStrategy = _prizeStrategy; emit PrizeStrategySet(address(_prizeStrategy)); } /// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship) /// @return An array of controlled token addresses function tokens() external override view returns (address[] memory) { return _tokens.addressArray(); } /// @dev Gets the current time as represented by the current block /// @return The timestamp of the current block function _currentTime() internal virtual view returns (uint256) { return block.timestamp; } /// @notice The timestamp at which an account's timelocked balance will be made available to sweep /// @param user The address of an account with timelocked assets /// @return The timestamp at which the locked assets will be made available function timelockBalanceAvailableAt(address user) external override view returns (uint256) { return _unlockTimestamps[user]; } /// @notice The balance of timelocked assets for an account /// @param user The address of an account with timelocked assets /// @return The amount of assets that have been timelocked function timelockBalanceOf(address user) external override view returns (uint256) { return _timelockBalances[user]; } /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function accountedBalance() external override view returns (uint256) { return _tokenTotalSupply(); } /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function _tokenTotalSupply() internal view returns (uint256) { uint256 total = timelockTotalSupply.add(reserveTotalSupply); address currentToken = _tokens.start(); while (currentToken != address(0) && currentToken != _tokens.end()) { total = total.add(IERC20Upgradeable(currentToken).totalSupply()); currentToken = _tokens.next(currentToken); } return total; } /// @dev Checks if the Prize Pool can receive liquidity based on the current cap /// @param _amount The amount of liquidity to be added to the Prize Pool /// @return True if the Prize Pool can receive the specified amount of liquidity function _canAddLiquidity(uint256 _amount) internal view returns (bool) { uint256 tokenTotalSupply = _tokenTotalSupply(); return (tokenTotalSupply.add(_amount) <= liquidityCap); } /// @dev Checks if a specific token is controlled by the Prize Pool /// @param controlledToken The address of the token to check /// @return True if the token is a controlled token, false otherwise function _isControlled(address controlledToken) internal view returns (bool) { return _tokens.contains(controlledToken); } /// @dev Function modifier to ensure usage of tokens controlled by the Prize Pool /// @param controlledToken The address of the token to check modifier onlyControlledToken(address controlledToken) { require(_isControlled(controlledToken), "PrizePool/unknown-token"); _; } /// @dev Function modifier to ensure caller is the prize-strategy modifier onlyPrizeStrategy() { require(_msgSender() == address(prizeStrategy), "PrizePool/only-prizeStrategy"); _; } /// @dev Function modifier to ensure the deposit amount does not exceed the liquidity cap (if set) modifier canAddLiquidity(uint256 _amount) { require(_canAddLiquidity(_amount), "PrizePool/exceeds-liquidity-cap"); _; } modifier onlyReserve() { ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup()); require(address(reserve) == msg.sender, "PrizePool/only-reserve"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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 pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165CheckerUpgradeable { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.0 <0.8.0; import "./external/openzeppelin/OpenZeppelinSafeMath_V3_3_0.sol"; /** * @author Brendan Asselstine * @notice Provides basic fixed point math calculations. * * This library calculates integer fractions by scaling values by 1e18 then performing standard integer math. */ library FixedPoint { using OpenZeppelinSafeMath_V3_3_0 for uint256; // The scale to use for fixed point numbers. Same as Ether for simplicity. uint256 internal constant SCALE = 1e18; /** * Calculates a Fixed18 mantissa given the numerator and denominator * * The mantissa = (numerator * 1e18) / denominator * * @param numerator The mantissa numerator * @param denominator The mantissa denominator * @return The mantissa of the fraction */ function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) { uint256 mantissa = numerator.mul(SCALE); mantissa = mantissa.div(denominator); return mantissa; } /** * Multiplies a Fixed18 number by an integer. * * @param b The whole integer to multiply * @param mantissa The Fixed18 number * @return An integer that is the result of multiplying the params. */ function multiplyUintByMantissa(uint256 b, uint256 mantissa) internal pure returns (uint256) { uint256 result = mantissa.mul(b); result = result.div(SCALE); return result; } /** * Divides an integer by a fixed point 18 mantissa * * @param dividend The integer to divide * @param mantissa The fixed point 18 number to serve as the divisor * @return An integer that is the result of dividing an integer by a fixed point 18 mantissa */ function divideUintByMantissa(uint256 dividend, uint256 mantissa) internal pure returns (uint256) { uint256 result = SCALE.mul(dividend); result = result.div(mantissa); return result; } } // SPDX-License-Identifier: MIT // NOTE: Copied from OpenZeppelin Contracts version 3.3.0 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 OpenZeppelinSafeMath_V3_3_0 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface RegistryInterface { function lookup() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface ReserveInterface { function reserveRateMantissa(address prizePool) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /// @title Defines the functions used to interact with a yield source. The Prize Pool inherits this contract. /// @notice Prize Pools subclasses need to implement this interface so that yield can be generated. abstract contract YieldSource { /// @notice Determines whether the passed token can be transferred out as an external award. /// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The /// prize strategy should not be allowed to move those tokens. /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal virtual view returns (bool); /// @notice Returns the ERC20 asset token used for deposits. /// @return The ERC20 asset token function _token() internal virtual view returns (IERC20Upgradeable); /// @notice Returns the total balance (in asset tokens). This includes the deposits and interest. /// @return The underlying balance of asset tokens function _balance() internal virtual returns (uint256); /// @notice Supplies asset tokens to the yield source. /// @param mintAmount The amount of asset tokens to be supplied function _supply(uint256 mintAmount) internal virtual; /// @notice Redeems asset tokens from the yield source. /// @param redeemAmount The amount of yield-bearing tokens to be redeemed /// @return The actual amount of tokens that were redeemed. function _redeem(uint256 redeemAmount) internal virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; /// @title An interface that allows a contract to listen to token mint, transfer and burn events. interface TokenListenerInterface is IERC165Upgradeable { /// @notice Called when tokens are minted. /// @param to The address of the receiver of the minted tokens. /// @param amount The amount of tokens being minted /// @param controlledToken The address of the token that is being minted /// @param referrer The address that referred the minting. function beforeTokenMint(address to, uint256 amount, address controlledToken, address referrer) external; /// @notice Called when tokens are transferred or burned. /// @param from The address of the sender of the token transfer /// @param to The address of the receiver of the token transfer. Will be the zero address if burning. /// @param amount The amount of tokens transferred /// @param controlledToken The address of the token that was transferred function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external; } pragma solidity ^0.6.12; library TokenListenerLibrary { /* * bytes4(keccak256('beforeTokenMint(address,uint256,address,address)')) == 0x4d7f3db0 * bytes4(keccak256('beforeTokenTransfer(address,address,uint256,address)')) == 0xb2210957 * * => 0x4d7f3db0 ^ 0xb2210957 == 0xff5e34e7 */ bytes4 public constant ERC165_INTERFACE_ID_TOKEN_LISTENER = 0xff5e34e7; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "./TokenControllerInterface.sol"; import "./ControlledTokenInterface.sol"; /// @title Controlled ERC20 Token /// @notice ERC20 Tokens with a controller for minting & burning contract ControlledToken is ERC20Upgradeable, ControlledTokenInterface { /// @notice Interface to the contract responsible for controlling mint/burn TokenControllerInterface public override controller; /// @notice Initializes the Controlled Token with Token Details and the Controller /// @param _name The name of the Token /// @param _symbol The symbol for the Token /// @param _decimals The number of decimals for the Token /// @param _controller Address of the Controller contract for minting & burning function initialize( string memory _name, string memory _symbol, uint8 _decimals, TokenControllerInterface _controller ) public virtual initializer { __ERC20_init(_name, _symbol); controller = _controller; _setupDecimals(_decimals); } /// @notice Allows the controller to mint tokens for a user account /// @dev May be overridden to provide more granular control over minting /// @param _user Address of the receiver of the minted tokens /// @param _amount Amount of tokens to mint function controllerMint(address _user, uint256 _amount) external virtual override onlyController { _mint(_user, _amount); } /// @notice Allows the controller to burn tokens from a user account /// @dev May be overridden to provide more granular control over burning /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurn(address _user, uint256 _amount) external virtual override onlyController { _burn(_user, _amount); } /// @notice Allows an operator via the controller to burn tokens on behalf of a user account /// @dev May be overridden to provide more granular control over operator-burning /// @param _operator Address of the operator performing the burn action via the controller contract /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurnFrom(address _operator, address _user, uint256 _amount) external virtual override onlyController { if (_operator != _user) { uint256 decreasedAllowance = allowance(_user, _operator).sub(_amount, "ControlledToken/exceeds-allowance"); _approve(_user, _operator, decreasedAllowance); } _burn(_user, _amount); } /// @dev Function modifier to ensure that the caller is the controller contract modifier onlyController { require(_msgSender() == address(controller), "ControlledToken/only-controller"); _; } /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// May be overridden to provide more granular control over operator-burning /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to Address of the account receiving the tokens (address(0x0) on burning) /// @param amount Amount of tokens being transferred function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { controller.beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Controlled ERC20 Token Interface /// @notice Required interface for Controlled ERC20 Tokens linked to a Prize Pool /// @dev Defines the spec required to be implemented by a Controlled ERC20 Token interface TokenControllerInterface { /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to Address of the account receiving the tokens (address(0x0) on burning) /// @param amount Amount of tokens being transferred function beforeTokenTransfer(address from, address to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./TokenControllerInterface.sol"; /// @title Controlled ERC20 Token /// @notice ERC20 Tokens with a controller for minting & burning interface ControlledTokenInterface is IERC20Upgradeable { /// @notice Interface to the contract responsible for controlling mint/burn function controller() external view returns (TokenControllerInterface); /// @notice Allows the controller to mint tokens for a user account /// @dev May be overridden to provide more granular control over minting /// @param _user Address of the receiver of the minted tokens /// @param _amount Amount of tokens to mint function controllerMint(address _user, uint256 _amount) external; /// @notice Allows the controller to burn tokens from a user account /// @dev May be overridden to provide more granular control over burning /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurn(address _user, uint256 _amount) external; /// @notice Allows an operator via the controller to burn tokens on behalf of a user account /// @dev May be overridden to provide more granular control over operator-burning /// @param _operator Address of the operator performing the burn action via the controller contract /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurnFrom(address _operator, address _user, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; /// @notice An efficient implementation of a singly linked list of addresses /// @dev A mapping(address => address) tracks the 'next' pointer. A special address called the SENTINEL is used to denote the beginning and end of the list. library MappedSinglyLinkedList { /// @notice The special value address used to denote the end of the list address public constant SENTINEL = address(0x1); /// @notice The data structure to use for the list. struct Mapping { uint256 count; mapping(address => address) addressMap; } /// @notice Initializes the list. /// @dev It is important that this is called so that the SENTINEL is correctly setup. function initialize(Mapping storage self) internal { require(self.count == 0, "Already init"); self.addressMap[SENTINEL] = SENTINEL; } function start(Mapping storage self) internal view returns (address) { return self.addressMap[SENTINEL]; } function next(Mapping storage self, address current) internal view returns (address) { return self.addressMap[current]; } function end(Mapping storage) internal pure returns (address) { return SENTINEL; } function addAddresses(Mapping storage self, address[] memory addresses) internal { for (uint256 i = 0; i < addresses.length; i++) { addAddress(self, addresses[i]); } } /// @notice Adds an address to the front of the list. /// @param self The Mapping struct that this function is attached to /// @param newAddress The address to shift to the front of the list function addAddress(Mapping storage self, address newAddress) internal { require(newAddress != SENTINEL && newAddress != address(0), "Invalid address"); require(self.addressMap[newAddress] == address(0), "Already added"); self.addressMap[newAddress] = self.addressMap[SENTINEL]; self.addressMap[SENTINEL] = newAddress; self.count = self.count + 1; } /// @notice Removes an address from the list /// @param self The Mapping struct that this function is attached to /// @param prevAddress The address that precedes the address to be removed. This may be the SENTINEL if at the start. /// @param addr The address to remove from the list. function removeAddress(Mapping storage self, address prevAddress, address addr) internal { require(addr != SENTINEL && addr != address(0), "Invalid address"); require(self.addressMap[prevAddress] == addr, "Invalid prevAddress"); self.addressMap[prevAddress] = self.addressMap[addr]; delete self.addressMap[addr]; self.count = self.count - 1; } /// @notice Determines whether the list contains the given address /// @param self The Mapping struct that this function is attached to /// @param addr The address to check /// @return True if the address is contained, false otherwise. function contains(Mapping storage self, address addr) internal view returns (bool) { return addr != SENTINEL && addr != address(0) && self.addressMap[addr] != address(0); } /// @notice Returns an address array of all the addresses in this list /// @dev Contains a for loop, so complexity is O(n) wrt the list size /// @param self The Mapping struct that this function is attached to /// @return An array of all the addresses function addressArray(Mapping storage self) internal view returns (address[] memory) { address[] memory array = new address[](self.count); uint256 count; address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { array[count] = currentAddress; currentAddress = self.addressMap[currentAddress]; count++; } return array; } /// @notice Removes every address from the list /// @param self The Mapping struct that this function is attached to function clearAll(Mapping storage self) internal { address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { address nextAddress = self.addressMap[currentAddress]; delete self.addressMap[currentAddress]; currentAddress = nextAddress; } self.addressMap[SENTINEL] = SENTINEL; self.count = 0; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../token/TokenListenerInterface.sol"; import "../token/ControlledTokenInterface.sol"; /// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool. /// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract. /// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens interface PrizePoolInterface { /// @notice Deposit assets into the Prize Pool in exchange for tokens /// @param to The address receiving the newly minted tokens /// @param amount The amount of assets to deposit /// @param controlledToken The address of the type of token the user is minting /// @param referrer The referrer of the deposit function depositTo( address to, uint256 amount, address controlledToken, address referrer ) external; /// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit. /// @param from The address to redeem tokens from. /// @param amount The amount of tokens to redeem for assets. /// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship) /// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn. /// @return The actual exit fee paid function withdrawInstantlyFrom( address from, uint256 amount, address controlledToken, uint256 maximumExitFee ) external returns (uint256); /// @notice Withdraw assets from the Prize Pool by placing them into the timelock. /// The timelock is used to ensure that the tickets have contributed their fair share of the prize. /// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them. /// If the existing timelocked funds are still locked, then the incoming /// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one. /// @param from The address to withdraw from /// @param amount The amount to withdraw /// @param controlledToken The type of token being withdrawn /// @return The timestamp from which the funds can be swept function withdrawWithTimelockFrom( address from, uint256 amount, address controlledToken ) external returns (uint256); function withdrawReserve(address to) external returns (uint256); /// @notice Returns the balance that is available to award. /// @dev captureAwardBalance() should be called first /// @return The total amount of assets to be awarded for the current prize function awardBalance() external view returns (uint256); /// @notice Captures any available interest as award balance. /// @dev This function also captures the reserve fees. /// @return The total amount of assets to be awarded for the current prize function captureAwardBalance() external returns (uint256); /// @notice Called by the prize strategy to award prizes. /// @dev The amount awarded must be less than the awardBalance() /// @param to The address of the winner that receives the award /// @param amount The amount of assets to be awarded /// @param controlledToken The address of the asset token being awarded function award( address to, uint256 amount, address controlledToken ) external; /// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything. /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function transferExternalERC20( address to, address externalToken, uint256 amount ) external; /// @notice Called by the Prize-Strategy to award external ERC20 prizes /// @dev Used to award any arbitrary tokens held by the Prize Pool /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function awardExternalERC20( address to, address externalToken, uint256 amount ) external; /// @notice Called by the prize strategy to award external ERC721 prizes /// @dev Used to award any arbitrary NFTs held by the Prize Pool /// @param to The address of the winner that receives the award /// @param externalToken The address of the external NFT token being awarded /// @param tokenIds An array of NFT Token IDs to be transferred function awardExternalERC721( address to, address externalToken, uint256[] calldata tokenIds ) external; /// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts /// @param users An array of account addresses to sweep balances for /// @return The total amount of assets swept from the Prize Pool function sweepTimelockBalances( address[] calldata users ) external returns (uint256); /// @notice Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds function calculateTimelockDuration( address from, address controlledToken, uint256 amount ) external returns ( uint256 durationSeconds, uint256 burnedCredit ); /// @notice Calculates the early exit fee for the given amount /// @param from The user who is withdrawing /// @param controlledToken The type of collateral being withdrawn /// @param amount The amount of collateral to be withdrawn /// @return exitFee The exit fee /// @return burnedCredit The user's credit that was burned function calculateEarlyExitFee( address from, address controlledToken, uint256 amount ) external returns ( uint256 exitFee, uint256 burnedCredit ); /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit. /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) external view returns (uint256 durationSeconds); /// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit. /// @param user The user whose credit balance should be returned /// @return The balance of the users credit function balanceOfCredit(address user, address controlledToken) external returns (uint256); /// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether). /// @param _controlledToken The controlled token for whom to set the credit plan /// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether). /// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether). function setCreditPlanOf( address _controlledToken, uint128 _creditRateMantissa, uint128 _creditLimitMantissa ) external; /// @notice Returns the credit rate of a controlled token /// @param controlledToken The controlled token to retrieve the credit rates for /// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee. /// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second. function creditPlanOf( address controlledToken ) external view returns ( uint128 creditLimitMantissa, uint128 creditRateMantissa ); /// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold /// @param _liquidityCap The new liquidity cap for the prize pool function setLiquidityCap(uint256 _liquidityCap) external; /// @notice Allows the Governor to add Controlled Tokens to the Prize Pool /// @param _controlledToken The address of the Controlled Token to add function addControlledToken(ControlledTokenInterface _controlledToken) external; /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy. Must implement TokenListenerInterface function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external; /// @dev Returns the address of the underlying ERC20 asset /// @return The address of the asset function token() external view returns (address); /// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship) /// @return An array of controlled token addresses function tokens() external view returns (address[] memory); /// @notice The timestamp at which an account's timelocked balance will be made available to sweep /// @param user The address of an account with timelocked assets /// @return The timestamp at which the locked assets will be made available function timelockBalanceAvailableAt(address user) external view returns (uint256); /// @notice The balance of timelocked assets for an account /// @param user The address of an account with timelocked assets /// @return The amount of assets that have been timelocked function timelockBalanceOf(address user) external view returns (uint256); /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function accountedBalance() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol"; import "../token/TokenListener.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../token/TokenControllerInterface.sol"; import "../token/ControlledToken.sol"; import "../token/TicketInterface.sol"; import "../prize-pool/PrizePool.sol"; import "../Constants.sol"; import "./PeriodicPrizeStrategyListenerInterface.sol"; import "./PeriodicPrizeStrategyListenerLibrary.sol"; /* solium-disable security/no-block-members */ abstract contract PeriodicPrizeStrategy is Initializable, OwnableUpgradeable, TokenListener { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using AddressUpgradeable for address; using ERC165CheckerUpgradeable for address; uint256 internal constant ETHEREUM_BLOCK_TIME_ESTIMATE_MANTISSA = 13.4 ether; event PrizePoolOpened( address indexed operator, uint256 indexed prizePeriodStartedAt ); event RngRequestFailed(); event PrizePoolAwardStarted( address indexed operator, address indexed prizePool, uint32 indexed rngRequestId, uint32 rngLockBlock ); event PrizePoolAwardCancelled( address indexed operator, address indexed prizePool, uint32 indexed rngRequestId, uint32 rngLockBlock ); event PrizePoolAwarded( address indexed operator, uint256 randomNumber ); event RngServiceUpdated( RNGInterface indexed rngService ); event TokenListenerUpdated( TokenListenerInterface indexed tokenListener ); event RngRequestTimeoutSet( uint32 rngRequestTimeout ); event PeriodicPrizeStrategyListenerSet( PeriodicPrizeStrategyListenerInterface indexed periodicPrizeStrategyListener ); event ExternalErc721AwardAdded( IERC721Upgradeable indexed externalErc721, uint256[] tokenIds ); event ExternalErc20AwardAdded( IERC20Upgradeable indexed externalErc20 ); event ExternalErc721AwardRemoved( IERC721Upgradeable indexed externalErc721Award ); event ExternalErc20AwardRemoved( IERC20Upgradeable indexed externalErc20Award ); event Initialized( uint256 prizePeriodStart, uint256 prizePeriodSeconds, PrizePool indexed prizePool, TicketInterface ticket, IERC20Upgradeable sponsorship, RNGInterface rng, IERC20Upgradeable[] externalErc20Awards ); struct RngRequest { uint32 id; uint32 lockBlock; uint32 requestedAt; } // Comptroller TokenListenerInterface public tokenListener; // Contract Interfaces PrizePool public prizePool; TicketInterface public ticket; IERC20Upgradeable public sponsorship; RNGInterface public rng; // Current RNG Request RngRequest internal rngRequest; /// @notice RNG Request Timeout. In fact, this is really a "complete award" timeout. /// If the rng completes the award can still be cancelled. uint32 public rngRequestTimeout; // Prize period uint256 public prizePeriodSeconds; uint256 public prizePeriodStartedAt; // External tokens awarded as part of prize MappedSinglyLinkedList.Mapping internal externalErc20s; MappedSinglyLinkedList.Mapping internal externalErc721s; // External NFT token IDs to be awarded // NFT Address => TokenIds mapping (IERC721Upgradeable => uint256[]) internal externalErc721TokenIds; /// @notice A listener that receives callbacks before certain events PeriodicPrizeStrategyListenerInterface public periodicPrizeStrategyListener; /// @notice Initializes a new strategy /// @param _prizePeriodStart The starting timestamp of the prize period. /// @param _prizePeriodSeconds The duration of the prize period in seconds /// @param _prizePool The prize pool to award /// @param _ticket The ticket to use to draw winners /// @param _sponsorship The sponsorship token /// @param _rng The RNG service to use function initialize ( uint256 _prizePeriodStart, uint256 _prizePeriodSeconds, PrizePool _prizePool, TicketInterface _ticket, IERC20Upgradeable _sponsorship, RNGInterface _rng, IERC20Upgradeable[] memory externalErc20Awards ) public initializer { require(_prizePeriodSeconds > 0, "PeriodicPrizeStrategy/prize-period-greater-than-zero"); require(address(_prizePool) != address(0), "PeriodicPrizeStrategy/prize-pool-not-zero"); require(address(_ticket) != address(0), "PeriodicPrizeStrategy/ticket-not-zero"); require(address(_sponsorship) != address(0), "PeriodicPrizeStrategy/sponsorship-not-zero"); require(address(_rng) != address(0), "PeriodicPrizeStrategy/rng-not-zero"); prizePool = _prizePool; ticket = _ticket; rng = _rng; sponsorship = _sponsorship; __Ownable_init(); Constants.REGISTRY.setInterfaceImplementer(address(this), Constants.TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); externalErc20s.initialize(); for (uint256 i = 0; i < externalErc20Awards.length; i++) { _addExternalErc20Award(externalErc20Awards[i]); } prizePeriodSeconds = _prizePeriodSeconds; prizePeriodStartedAt = _prizePeriodStart; externalErc721s.initialize(); // 30 min timeout _setRngRequestTimeout(1800); emit Initialized( _prizePeriodStart, _prizePeriodSeconds, _prizePool, _ticket, _sponsorship, _rng, externalErc20Awards ); emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt); } function _distribute(uint256 randomNumber) internal virtual; /// @notice Calculates and returns the currently accrued prize /// @return The current prize size function currentPrize() public view returns (uint256) { return prizePool.awardBalance(); } /// @notice Allows the owner to set the token listener /// @param _tokenListener A contract that implements the token listener interface. function setTokenListener(TokenListenerInterface _tokenListener) external onlyOwner requireAwardNotInProgress { require(address(0) == address(_tokenListener) || address(_tokenListener).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PeriodicPrizeStrategy/token-listener-invalid"); tokenListener = _tokenListener; emit TokenListenerUpdated(tokenListener); } /// @notice Estimates the remaining blocks until the prize given a number of seconds per block /// @param secondsPerBlockMantissa The number of seconds per block to use for the calculation. Should be a fixed point 18 number like Ether. /// @return The estimated number of blocks remaining until the prize can be awarded. function estimateRemainingBlocksToPrize(uint256 secondsPerBlockMantissa) public view returns (uint256) { return FixedPoint.divideUintByMantissa( _prizePeriodRemainingSeconds(), secondsPerBlockMantissa ); } /// @notice Returns the number of seconds remaining until the prize can be awarded. /// @return The number of seconds remaining until the prize can be awarded. function prizePeriodRemainingSeconds() external view returns (uint256) { return _prizePeriodRemainingSeconds(); } /// @notice Returns the number of seconds remaining until the prize can be awarded. /// @return The number of seconds remaining until the prize can be awarded. function _prizePeriodRemainingSeconds() internal view returns (uint256) { uint256 endAt = _prizePeriodEndAt(); uint256 time = _currentTime(); if (time > endAt) { return 0; } return endAt.sub(time); } /// @notice Returns whether the prize period is over /// @return True if the prize period is over, false otherwise function isPrizePeriodOver() external view returns (bool) { return _isPrizePeriodOver(); } /// @notice Returns whether the prize period is over /// @return True if the prize period is over, false otherwise function _isPrizePeriodOver() internal view returns (bool) { return _currentTime() >= _prizePeriodEndAt(); } /// @notice Awards collateral as tickets to a user /// @param user The user to whom the tickets are minted /// @param amount The amount of interest to mint as tickets. function _awardTickets(address user, uint256 amount) internal { prizePool.award(user, amount, address(ticket)); } /// @notice Awards all external tokens with non-zero balances to the given user. The external tokens must be held by the PrizePool contract. /// @param winner The user to transfer the tokens to function _awardAllExternalTokens(address winner) internal { _awardExternalErc20s(winner); _awardExternalErc721s(winner); } /// @notice Awards all external ERC20 tokens with non-zero balances to the given user. /// The external tokens must be held by the PrizePool contract. /// @param winner The user to transfer the tokens to function _awardExternalErc20s(address winner) internal { address currentToken = externalErc20s.start(); while (currentToken != address(0) && currentToken != externalErc20s.end()) { uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool)); if (balance > 0) { prizePool.awardExternalERC20(winner, currentToken, balance); } currentToken = externalErc20s.next(currentToken); } } /// @notice Awards all external ERC721 tokens to the given user. /// The external tokens must be held by the PrizePool contract. /// @dev The list of ERC721s is reset after every award /// @param winner The user to transfer the tokens to function _awardExternalErc721s(address winner) internal { address currentToken = externalErc721s.start(); while (currentToken != address(0) && currentToken != externalErc721s.end()) { uint256 balance = IERC721Upgradeable(currentToken).balanceOf(address(prizePool)); if (balance > 0) { prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[IERC721Upgradeable(currentToken)]); _removeExternalErc721AwardTokens(IERC721Upgradeable(currentToken)); } currentToken = externalErc721s.next(currentToken); } externalErc721s.clearAll(); } /// @notice Returns the timestamp at which the prize period ends /// @return The timestamp at which the prize period ends. function prizePeriodEndAt() external view returns (uint256) { // current prize started at is non-inclusive, so add one return _prizePeriodEndAt(); } /// @notice Returns the timestamp at which the prize period ends /// @return The timestamp at which the prize period ends. function _prizePeriodEndAt() internal view returns (uint256) { // current prize started at is non-inclusive, so add one return prizePeriodStartedAt.add(prizePeriodSeconds); } /// @notice Called by the PrizePool for transfers of controlled tokens /// @dev Note that this is only for *transfers*, not mints or burns /// @param controlledToken The type of collateral that is being sent function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external override onlyPrizePool { require(from != to, "PeriodicPrizeStrategy/transfer-to-self"); if (controlledToken == address(ticket)) { _requireAwardNotInProgress(); } if (address(tokenListener) != address(0)) { tokenListener.beforeTokenTransfer(from, to, amount, controlledToken); } } /// @notice Called by the PrizePool when minting controlled tokens /// @param controlledToken The type of collateral that is being minted function beforeTokenMint( address to, uint256 amount, address controlledToken, address referrer ) external override onlyPrizePool { if (controlledToken == address(ticket)) { _requireAwardNotInProgress(); } if (address(tokenListener) != address(0)) { tokenListener.beforeTokenMint(to, amount, controlledToken, referrer); } } /// @notice returns the current time. Used for testing. /// @return The current time (block.timestamp) function _currentTime() internal virtual view returns (uint256) { return block.timestamp; } /// @notice returns the current time. Used for testing. /// @return The current time (block.timestamp) function _currentBlock() internal virtual view returns (uint256) { return block.number; } /// @notice Starts the award process by starting random number request. The prize period must have ended. /// @dev The RNG-Request-Fee is expected to be held within this contract before calling this function function startAward() external requireCanStartAward { (address feeToken, uint256 requestFee) = rng.getRequestFee(); if (feeToken != address(0) && requestFee > 0) { IERC20Upgradeable(feeToken).approve(address(rng), requestFee); } (uint32 requestId, uint32 lockBlock) = rng.requestRandomNumber(); rngRequest.id = requestId; rngRequest.lockBlock = lockBlock; rngRequest.requestedAt = _currentTime().toUint32(); emit PrizePoolAwardStarted(_msgSender(), address(prizePool), requestId, lockBlock); } /// @notice Can be called by anyone to unlock the tickets if the RNG has timed out. function cancelAward() public { require(isRngTimedOut(), "PeriodicPrizeStrategy/rng-not-timedout"); uint32 requestId = rngRequest.id; uint32 lockBlock = rngRequest.lockBlock; delete rngRequest; emit RngRequestFailed(); emit PrizePoolAwardCancelled(msg.sender, address(prizePool), requestId, lockBlock); } /// @notice Completes the award process and awards the winners. The random number must have been requested and is now available. function completeAward() external requireCanCompleteAward { uint256 randomNumber = rng.randomNumber(rngRequest.id); delete rngRequest; _distribute(randomNumber); if (address(periodicPrizeStrategyListener) != address(0)) { periodicPrizeStrategyListener.afterPrizePoolAwarded(randomNumber, prizePeriodStartedAt); } // to avoid clock drift, we should calculate the start time based on the previous period start time. prizePeriodStartedAt = _calculateNextPrizePeriodStartTime(_currentTime()); emit PrizePoolAwarded(_msgSender(), randomNumber); emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt); } /// @notice Allows the owner to set a listener for prize strategy callbacks. /// @param _periodicPrizeStrategyListener The address of the listener contract function setPeriodicPrizeStrategyListener(PeriodicPrizeStrategyListenerInterface _periodicPrizeStrategyListener) external onlyOwner requireAwardNotInProgress { require( address(0) == address(_periodicPrizeStrategyListener) || address(_periodicPrizeStrategyListener).supportsInterface(PeriodicPrizeStrategyListenerLibrary.ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER), "PeriodicPrizeStrategy/prizeStrategyListener-invalid" ); periodicPrizeStrategyListener = _periodicPrizeStrategyListener; emit PeriodicPrizeStrategyListenerSet(_periodicPrizeStrategyListener); } function _calculateNextPrizePeriodStartTime(uint256 currentTime) internal view returns (uint256) { uint256 elapsedPeriods = currentTime.sub(prizePeriodStartedAt).div(prizePeriodSeconds); return prizePeriodStartedAt.add(elapsedPeriods.mul(prizePeriodSeconds)); } /// @notice Calculates when the next prize period will start /// @param currentTime The timestamp to use as the current time /// @return The timestamp at which the next prize period would start function calculateNextPrizePeriodStartTime(uint256 currentTime) external view returns (uint256) { return _calculateNextPrizePeriodStartTime(currentTime); } /// @notice Returns whether an award process can be started /// @return True if an award can be started, false otherwise. function canStartAward() external view returns (bool) { return _isPrizePeriodOver() && !isRngRequested(); } /// @notice Returns whether an award process can be completed /// @return True if an award can be completed, false otherwise. function canCompleteAward() external view returns (bool) { return isRngRequested() && isRngCompleted(); } /// @notice Returns whether a random number has been requested /// @return True if a random number has been requested, false otherwise. function isRngRequested() public view returns (bool) { return rngRequest.id != 0; } /// @notice Returns whether the random number request has completed. /// @return True if a random number request has completed, false otherwise. function isRngCompleted() public view returns (bool) { return rng.isRequestComplete(rngRequest.id); } /// @notice Returns the block number that the current RNG request has been locked to /// @return The block number that the RNG request is locked to function getLastRngLockBlock() external view returns (uint32) { return rngRequest.lockBlock; } /// @notice Returns the current RNG Request ID /// @return The current Request ID function getLastRngRequestId() external view returns (uint32) { return rngRequest.id; } /// @notice Sets the RNG service that the Prize Strategy is connected to /// @param rngService The address of the new RNG service interface function setRngService(RNGInterface rngService) external onlyOwner requireAwardNotInProgress { require(!isRngRequested(), "PeriodicPrizeStrategy/rng-in-flight"); rng = rngService; emit RngServiceUpdated(rngService); } function setRngRequestTimeout(uint32 _rngRequestTimeout) external onlyOwner requireAwardNotInProgress { _setRngRequestTimeout(_rngRequestTimeout); } function _setRngRequestTimeout(uint32 _rngRequestTimeout) internal { require(_rngRequestTimeout > 60, "PeriodicPrizeStrategy/rng-timeout-gt-60-secs"); rngRequestTimeout = _rngRequestTimeout; emit RngRequestTimeoutSet(rngRequestTimeout); } /// @notice Gets the current list of External ERC20 tokens that will be awarded with the current prize /// @return An array of External ERC20 token addresses function getExternalErc20Awards() external view returns (address[] memory) { return externalErc20s.addressArray(); } /// @notice Adds an external ERC20 token type as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can assign external tokens, /// and they must be approved by the Prize-Pool /// @param _externalErc20 The address of an ERC20 token to be awarded function addExternalErc20Award(IERC20Upgradeable _externalErc20) external onlyOwnerOrListener requireAwardNotInProgress { _addExternalErc20Award(_externalErc20); } function _addExternalErc20Award(IERC20Upgradeable _externalErc20) internal { require(address(_externalErc20).isContract(), "PeriodicPrizeStrategy/erc20-null"); require(prizePool.canAwardExternal(address(_externalErc20)), "PeriodicPrizeStrategy/cannot-award-external"); (bool succeeded, bytes memory returnValue) = address(_externalErc20).staticcall(abi.encodeWithSignature("totalSupply()")); require(succeeded, "PeriodicPrizeStrategy/erc20-invalid"); externalErc20s.addAddress(address(_externalErc20)); emit ExternalErc20AwardAdded(_externalErc20); } function addExternalErc20Awards(IERC20Upgradeable[] calldata _externalErc20s) external onlyOwnerOrListener requireAwardNotInProgress { for (uint256 i = 0; i < _externalErc20s.length; i++) { _addExternalErc20Award(_externalErc20s[i]); } } /// @notice Removes an external ERC20 token type as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can remove external tokens /// @param _externalErc20 The address of an ERC20 token to be removed /// @param _prevExternalErc20 The address of the previous ERC20 token in the `externalErc20s` list. /// If the ERC20 is the first address, then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001 function removeExternalErc20Award(IERC20Upgradeable _externalErc20, IERC20Upgradeable _prevExternalErc20) external onlyOwner requireAwardNotInProgress { externalErc20s.removeAddress(address(_prevExternalErc20), address(_externalErc20)); emit ExternalErc20AwardRemoved(_externalErc20); } /// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize /// @return An array of External ERC721 token addresses function getExternalErc721Awards() external view returns (address[] memory) { return externalErc721s.addressArray(); } /// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize /// @return An array of External ERC721 token addresses function getExternalErc721AwardTokenIds(IERC721Upgradeable _externalErc721) external view returns (uint256[] memory) { return externalErc721TokenIds[_externalErc721]; } /// @notice Adds an external ERC721 token as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can assign external tokens, /// and they must be approved by the Prize-Pool /// NOTE: The NFT must already be owned by the Prize-Pool /// @param _externalErc721 The address of an ERC721 token to be awarded /// @param _tokenIds An array of token IDs of the ERC721 to be awarded function addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256[] calldata _tokenIds) external onlyOwnerOrListener requireAwardNotInProgress { require(prizePool.canAwardExternal(address(_externalErc721)), "PeriodicPrizeStrategy/cannot-award-external"); require(address(_externalErc721).supportsInterface(Constants.ERC165_INTERFACE_ID_ERC721), "PeriodicPrizeStrategy/erc721-invalid"); if (!externalErc721s.contains(address(_externalErc721))) { externalErc721s.addAddress(address(_externalErc721)); } for (uint256 i = 0; i < _tokenIds.length; i++) { _addExternalErc721Award(_externalErc721, _tokenIds[i]); } emit ExternalErc721AwardAdded(_externalErc721, _tokenIds); } function _addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256 _tokenId) internal { require(IERC721Upgradeable(_externalErc721).ownerOf(_tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token"); for (uint256 i = 0; i < externalErc721TokenIds[_externalErc721].length; i++) { if (externalErc721TokenIds[_externalErc721][i] == _tokenId) { revert("PeriodicPrizeStrategy/erc721-duplicate"); } } externalErc721TokenIds[_externalErc721].push(_tokenId); } /// @notice Removes an external ERC721 token as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can remove external tokens /// @param _externalErc721 The address of an ERC721 token to be removed /// @param _prevExternalErc721 The address of the previous ERC721 token in the list. /// If no previous, then pass the SENTINEL address: 0x0000000000000000000000000000000000000001 function removeExternalErc721Award( IERC721Upgradeable _externalErc721, IERC721Upgradeable _prevExternalErc721 ) external onlyOwner requireAwardNotInProgress { externalErc721s.removeAddress(address(_prevExternalErc721), address(_externalErc721)); _removeExternalErc721AwardTokens(_externalErc721); } function _removeExternalErc721AwardTokens( IERC721Upgradeable _externalErc721 ) internal { delete externalErc721TokenIds[_externalErc721]; emit ExternalErc721AwardRemoved(_externalErc721); } /// @notice Allows the owner to transfer out external ERC20 tokens /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything. /// @param to The address that receives the tokens /// @param externalToken The address of the external asset token being transferred /// @param amount The amount of external assets to be transferred function transferExternalERC20( address to, address externalToken, uint256 amount ) external onlyOwner requireAwardNotInProgress { prizePool.transferExternalERC20(to, externalToken, amount); } function _requireAwardNotInProgress() internal view { uint256 currentBlock = _currentBlock(); require(rngRequest.lockBlock == 0 || currentBlock < rngRequest.lockBlock, "PeriodicPrizeStrategy/rng-in-flight"); } function isRngTimedOut() public view returns (bool) { if (rngRequest.requestedAt == 0) { return false; } else { return _currentTime() > uint256(rngRequestTimeout).add(rngRequest.requestedAt); } } modifier onlyOwnerOrListener() { require(_msgSender() == owner() || _msgSender() == address(periodicPrizeStrategyListener), "PeriodicPrizeStrategy/only-owner-or-listener"); _; } modifier requireAwardNotInProgress() { _requireAwardNotInProgress(); _; } modifier requireCanStartAward() { require(_isPrizePeriodOver(), "PeriodicPrizeStrategy/prize-period-not-over"); require(!isRngRequested(), "PeriodicPrizeStrategy/rng-already-requested"); _; } modifier requireCanCompleteAward() { require(isRngRequested(), "PeriodicPrizeStrategy/rng-not-requested"); require(isRngCompleted(), "PeriodicPrizeStrategy/rng-not-complete"); _; } modifier onlyPrizePool() { require(_msgSender() == address(prizePool), "PeriodicPrizeStrategy/only-prize-pool"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0; /// @title Random Number Generator Interface /// @notice Provides an interface for requesting random numbers from 3rd-party RNG services (Chainlink VRF, Starkware VDF, etc..) interface RNGInterface { /// @notice Emitted when a new request for a random number has been submitted /// @param requestId The indexed ID of the request used to get the results of the RNG service /// @param sender The indexed address of the sender of the request event RandomNumberRequested(uint32 indexed requestId, address indexed sender); /// @notice Emitted when an existing request for a random number has been completed /// @param requestId The indexed ID of the request used to get the results of the RNG service /// @param randomNumber The random number produced by the 3rd-party service event RandomNumberCompleted(uint32 indexed requestId, uint256 randomNumber); /// @notice Gets the last request id used by the RNG service /// @return requestId The last request id used in the last request function getLastRequestId() external view returns (uint32 requestId); /// @notice Gets the Fee for making a Request against an RNG service /// @return feeToken The address of the token that is used to pay fees /// @return requestFee The fee required to be paid to make a request function getRequestFee() external view returns (address feeToken, uint256 requestFee); /// @notice Sends a request for a random number to the 3rd-party service /// @dev Some services will complete the request immediately, others may have a time-delay /// @dev Some services require payment in the form of a token, such as $LINK for Chainlink VRF /// @return requestId The ID of the request used to get the results of the RNG service /// @return lockBlock The block number at which the RNG service will start generating time-delayed randomness. The calling contract /// should "lock" all activity until the result is available via the `requestId` function requestRandomNumber() external returns (uint32 requestId, uint32 lockBlock); /// @notice Checks if the request for randomness from the 3rd-party service has completed /// @dev For time-delayed requests, this function is used to check/confirm completion /// @param requestId The ID of the request used to get the results of the RNG service /// @return isCompleted True if the request has completed and a random number is available, false otherwise function isRequestComplete(uint32 requestId) external view returns (bool isCompleted); /// @notice Gets the random number produced by the 3rd-party service /// @param requestId The ID of the request used to get the results of the RNG service /// @return randomNum The random number function randomNumber(uint32 requestId) external returns (uint256 randomNum); } pragma solidity ^0.6.4; import "./TokenListenerInterface.sol"; import "./TokenListenerLibrary.sol"; import "../Constants.sol"; abstract contract TokenListener is TokenListenerInterface { function supportsInterface(bytes4 interfaceId) external override view returns (bool) { return ( interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 || interfaceId == TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER ); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC1820RegistryUpgradeable.sol"; library Constants { IERC1820RegistryUpgradeable public constant REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensSender") bytes32 public constant TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 public constant TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); bytes32 public constant ACCEPT_MAGIC = 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4; bytes4 public constant ERC165_INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 public constant ERC165_INTERFACE_ID_ERC721 = 0x80ac58cd; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820RegistryUpgradeable { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface TicketInterface { /// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply. /// @param randomNumber The random number to use to select a user. /// @return The winner function draw(uint256 randomNumber) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; /* solium-disable security/no-block-members */ interface PeriodicPrizeStrategyListenerInterface is IERC165Upgradeable { function afterPrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external; } pragma solidity ^0.6.12; library PeriodicPrizeStrategyListenerLibrary { /* * bytes4(keccak256('afterPrizePoolAwarded(uint256,uint256)')) == 0x575072c6 */ bytes4 public constant ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER = 0x575072c6; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./CompoundPrizePool.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title Compound Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new Compound Prize Pools contract CompoundPrizePoolProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools CompoundPrizePool public instance; /// @notice Initializes the Factory with an instance of the Compound Prize Pool constructor () public { instance = new CompoundPrizePool(); } /// @notice Creates a new Compound Prize Pool as a proxy of the template instance /// @return A reference to the new proxied Compound Prize Pool function create() external returns (CompoundPrizePool) { return CompoundPrizePool(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../../external/compound/CTokenInterface.sol"; import "../PrizePool.sol"; /// @title Prize Pool with Compound's cToken /// @notice Manages depositing and withdrawing assets from the Prize Pool contract CompoundPrizePool is PrizePool { using SafeMathUpgradeable for uint256; event CompoundPrizePoolInitialized(address indexed cToken); /// @notice Interface for the Yield-bearing cToken by Compound CTokenInterface public cToken; /// @notice Initializes the Prize Pool and Yield Service with the required contract connections /// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool /// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount /// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be /// @param _cToken Address of the Compound cToken interface function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration, CTokenInterface _cToken ) public initializer { PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa, _maxTimelockDuration ); cToken = _cToken; emit CompoundPrizePoolInitialized(address(cToken)); } /// @dev Gets the balance of the underlying assets held by the Yield Service /// @return The underlying balance of asset tokens function _balance() internal override returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens /// to be held in escrow by the Yield Service /// @param amount The amount of asset tokens to be supplied function _supply(uint256 amount) internal override { _token().approve(address(cToken), amount); require(cToken.mint(amount) == 0, "CompoundPrizePool/mint-failed"); } /// @dev Checks with the Prize Pool if a specific token type may be awarded as a prize enhancement /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal override view returns (bool) { return _externalToken != address(cToken); } /// @dev Allows a user to redeem yield-bearing tokens in exchange for the underlying /// asset tokens held in escrow by the Yield Service /// @param amount The amount of underlying tokens to be redeemed /// @return The actual amount of tokens transferred function _redeem(uint256 amount) internal override returns (uint256) { IERC20Upgradeable assetToken = _token(); uint256 before = assetToken.balanceOf(address(this)); require(cToken.redeemUnderlying(amount) == 0, "CompoundPrizePool/redeem-failed"); uint256 diff = assetToken.balanceOf(address(this)).sub(before); return diff; } /// @dev Gets the underlying asset token used by the Yield Service /// @return A reference to the interface of the underling asset token function _token() internal override view returns (IERC20Upgradeable) { return IERC20Upgradeable(cToken.underlying()); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface CTokenInterface is IERC20Upgradeable { function decimals() external view returns (uint8); function totalSupply() external override view returns (uint256); function underlying() external view returns (address); function balanceOfUnderlying(address owner) external returns (uint256); function supplyRatePerBlock() external returns (uint256); function exchangeRateCurrent() external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function balanceOf(address user) external override view returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); } pragma solidity >=0.6.0 <0.7.0; // solium-disable security/no-inline-assembly // solium-disable security/no-low-level-calls contract ProxyFactory { event ProxyCreated(address proxy); function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) { // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol bytes20 targetBytes = bytes20(_logic); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } emit ProxyCreated(address(proxy)); if(_data.length > 0) { (bool success,) = proxy.call(_data); require(success, "ProxyFactory/constructor-call-failed"); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../token/ControlledTokenProxyFactory.sol"; import "../token/TicketProxyFactory.sol"; /* solium-disable security/no-block-members */ contract ControlledTokenBuilder { event CreatedControlledToken(address indexed token); event CreatedTicket(address indexed token); ControlledTokenProxyFactory public controlledTokenProxyFactory; TicketProxyFactory public ticketProxyFactory; struct ControlledTokenConfig { string name; string symbol; uint8 decimals; TokenControllerInterface controller; } constructor ( ControlledTokenProxyFactory _controlledTokenProxyFactory, TicketProxyFactory _ticketProxyFactory ) public { require(address(_controlledTokenProxyFactory) != address(0), "ControlledTokenBuilder/controlledTokenProxyFactory-not-zero"); require(address(_ticketProxyFactory) != address(0), "ControlledTokenBuilder/ticketProxyFactory-not-zero"); controlledTokenProxyFactory = _controlledTokenProxyFactory; ticketProxyFactory = _ticketProxyFactory; } function createControlledToken( ControlledTokenConfig calldata config ) external returns (ControlledToken) { ControlledToken token = controlledTokenProxyFactory.create(); token.initialize( config.name, config.symbol, config.decimals, config.controller ); emit CreatedControlledToken(address(token)); return token; } function createTicket( ControlledTokenConfig calldata config ) external returns (Ticket) { Ticket token = ticketProxyFactory.create(); token.initialize( config.name, config.symbol, config.decimals, config.controller ); emit CreatedTicket(address(token)); return token; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./ControlledToken.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Controlled ERC20 Token Factory /// @notice Minimal proxy pattern for creating new Controlled ERC20 Tokens contract ControlledTokenProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied tokens ControlledToken public instance; /// @notice Initializes the Factory with an instance of the Controlled ERC20 Token constructor () public { instance = new ControlledToken(); } /// @notice Creates a new Controlled ERC20 Token as a proxy of the template instance /// @return A reference to the new proxied Controlled ERC20 Token function create() external returns (ControlledToken) { return ControlledToken(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "./Ticket.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Controlled ERC20 Token Factory /// @notice Minimal proxy pattern for creating new Controlled ERC20 Tokens contract TicketProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied tokens Ticket public instance; /// @notice Initializes the Factory with an instance of the Controlled ERC20 Token constructor () public { instance = new Ticket(); } /// @notice Creates a new Controlled ERC20 Token as a proxy of the template instance /// @return A reference to the new proxied Controlled ERC20 Token function create() external returns (Ticket) { return Ticket(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "sortition-sum-tree-factory/contracts/SortitionSumTreeFactory.sol"; import "@pooltogether/uniform-random-number/contracts/UniformRandomNumber.sol"; import "./ControlledToken.sol"; import "./TicketInterface.sol"; contract Ticket is ControlledToken, TicketInterface { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; bytes32 constant private TREE_KEY = keccak256("PoolTogether/Ticket"); uint256 constant private MAX_TREE_LEAVES = 5; // Ticket-weighted odds SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees; /// @notice Initializes the Controlled Token with Token Details and the Controller /// @param _name The name of the Token /// @param _symbol The symbol for the Token /// @param _decimals The number of decimals for the Token /// @param _controller Address of the Controller contract for minting & burning function initialize( string memory _name, string memory _symbol, uint8 _decimals, TokenControllerInterface _controller ) public virtual override initializer { super.initialize(_name, _symbol, _decimals, _controller); sortitionSumTrees.createTree(TREE_KEY, MAX_TREE_LEAVES); } /// @notice Returns the user's chance of winning. function chanceOf(address user) external view returns (uint256) { return sortitionSumTrees.stakeOf(TREE_KEY, bytes32(uint256(user))); } /// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply. /// @param randomNumber The random number to use to select a user. /// @return The winner function draw(uint256 randomNumber) external view override returns (address) { uint256 bound = totalSupply(); address selected; if (bound == 0) { selected = address(0); } else { uint256 token = UniformRandomNumber.uniform(randomNumber, bound); selected = address(uint256(sortitionSumTrees.draw(TREE_KEY, token))); } return selected; } /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// May be overridden to provide more granular control over operator-burning /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to Address of the account receiving the tokens (address(0x0) on burning) /// @param amount Amount of tokens being transferred function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); // optimize: ignore transfers to self if (from == to) { return; } if (from != address(0)) { uint256 fromBalance = balanceOf(from).sub(amount); sortitionSumTrees.set(TREE_KEY, fromBalance, bytes32(uint256(from))); } if (to != address(0)) { uint256 toBalance = balanceOf(to).add(amount); sortitionSumTrees.set(TREE_KEY, toBalance, bytes32(uint256(to))); } } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ pragma solidity ^0.6.0; /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <epiquerass@gmail.com> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack = new uint[](0); tree.nodes = new uint[](0); tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.pop(); tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return startIndex The index at which leaves start * @return values The values of the returned leaves * @return hasMore Whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return ID The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return value The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (tree.nodes.length == 0) { return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.0 <0.8.0; /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { require(_upperBound > 0, "UniformRand/min-bound"); uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "./ControlledTokenBuilder.sol"; import "../prize-strategy/multiple-winners/MultipleWinnersProxyFactory.sol"; /* solium-disable security/no-block-members */ contract MultipleWinnersBuilder { event MultipleWinnersCreated(address indexed prizeStrategy); struct MultipleWinnersConfig { RNGInterface rngService; uint256 prizePeriodStart; uint256 prizePeriodSeconds; string ticketName; string ticketSymbol; string sponsorshipName; string sponsorshipSymbol; uint256 ticketCreditLimitMantissa; uint256 ticketCreditRateMantissa; uint256 numberOfWinners; bool splitExternalErc20Awards; } MultipleWinnersProxyFactory public multipleWinnersProxyFactory; ControlledTokenBuilder public controlledTokenBuilder; constructor ( MultipleWinnersProxyFactory _multipleWinnersProxyFactory, ControlledTokenBuilder _controlledTokenBuilder ) public { require(address(_multipleWinnersProxyFactory) != address(0), "MultipleWinnersBuilder/multipleWinnersProxyFactory-not-zero"); require(address(_controlledTokenBuilder) != address(0), "MultipleWinnersBuilder/token-builder-not-zero"); multipleWinnersProxyFactory = _multipleWinnersProxyFactory; controlledTokenBuilder = _controlledTokenBuilder; } function createMultipleWinners( PrizePool prizePool, MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals, address owner ) external returns (MultipleWinners) { MultipleWinners mw = multipleWinnersProxyFactory.create(); Ticket ticket = _createTicket( prizeStrategyConfig.ticketName, prizeStrategyConfig.ticketSymbol, decimals, prizePool ); ControlledToken sponsorship = _createSponsorship( prizeStrategyConfig.sponsorshipName, prizeStrategyConfig.sponsorshipSymbol, decimals, prizePool ); mw.initializeMultipleWinners( prizeStrategyConfig.prizePeriodStart, prizeStrategyConfig.prizePeriodSeconds, prizePool, ticket, sponsorship, prizeStrategyConfig.rngService, prizeStrategyConfig.numberOfWinners ); if (prizeStrategyConfig.splitExternalErc20Awards) { mw.setSplitExternalErc20Awards(true); } mw.transferOwnership(owner); emit MultipleWinnersCreated(address(mw)); return mw; } function createMultipleWinnersFromExistingPrizeStrategy( PeriodicPrizeStrategy prizeStrategy, uint256 numberOfWinners ) external returns (MultipleWinners) { MultipleWinners mw = multipleWinnersProxyFactory.create(); mw.initializeMultipleWinners( prizeStrategy.prizePeriodStartedAt(), prizeStrategy.prizePeriodSeconds(), prizeStrategy.prizePool(), prizeStrategy.ticket(), prizeStrategy.sponsorship(), prizeStrategy.rng(), numberOfWinners ); mw.transferOwnership(msg.sender); emit MultipleWinnersCreated(address(mw)); return mw; } function _createTicket( string memory name, string memory token, uint8 decimals, PrizePool prizePool ) internal returns (Ticket) { return controlledTokenBuilder.createTicket( ControlledTokenBuilder.ControlledTokenConfig( name, token, decimals, prizePool ) ); } function _createSponsorship( string memory name, string memory token, uint8 decimals, PrizePool prizePool ) internal returns (ControlledToken) { return controlledTokenBuilder.createControlledToken( ControlledTokenBuilder.ControlledTokenConfig( name, token, decimals, prizePool ) ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./MultipleWinners.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy. contract MultipleWinnersProxyFactory is ProxyFactory { MultipleWinners public instance; constructor () public { instance = new MultipleWinners(); } function create() external returns (MultipleWinners) { return MultipleWinners(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../PeriodicPrizeStrategy.sol"; contract MultipleWinners is PeriodicPrizeStrategy { uint256 internal __numberOfWinners; bool public splitExternalErc20Awards; event SplitExternalErc20AwardsSet(bool splitExternalErc20Awards); event NumberOfWinnersSet(uint256 numberOfWinners); event NoWinners(); function initializeMultipleWinners ( uint256 _prizePeriodStart, uint256 _prizePeriodSeconds, PrizePool _prizePool, TicketInterface _ticket, IERC20Upgradeable _sponsorship, RNGInterface _rng, uint256 _numberOfWinners ) public initializer { IERC20Upgradeable[] memory _externalErc20Awards; PeriodicPrizeStrategy.initialize( _prizePeriodStart, _prizePeriodSeconds, _prizePool, _ticket, _sponsorship, _rng, _externalErc20Awards ); _setNumberOfWinners(_numberOfWinners); } function setSplitExternalErc20Awards(bool _splitExternalErc20Awards) external onlyOwner requireAwardNotInProgress { splitExternalErc20Awards = _splitExternalErc20Awards; emit SplitExternalErc20AwardsSet(splitExternalErc20Awards); } function setNumberOfWinners(uint256 count) external onlyOwner requireAwardNotInProgress { _setNumberOfWinners(count); } function _setNumberOfWinners(uint256 count) internal { require(count > 0, "MultipleWinners/winners-gte-one"); __numberOfWinners = count; emit NumberOfWinnersSet(count); } function numberOfWinners() external view returns (uint256) { return __numberOfWinners; } function _distribute(uint256 randomNumber) internal override { uint256 prize = prizePool.captureAwardBalance(); // main winner is simply the first that is drawn address mainWinner = ticket.draw(randomNumber); // If drawing yields no winner, then there is no one to pick if (mainWinner == address(0)) { emit NoWinners(); return; } // main winner gets all external ERC721 tokens _awardExternalErc721s(mainWinner); address[] memory winners = new address[](__numberOfWinners); winners[0] = mainWinner; uint256 nextRandom = randomNumber; for (uint256 winnerCount = 1; winnerCount < __numberOfWinners; winnerCount++) { // add some arbitrary numbers to the previous random number to ensure no matches with the UniformRandomNumber lib bytes32 nextRandomHash = keccak256(abi.encodePacked(nextRandom + 499 + winnerCount*521)); nextRandom = uint256(nextRandomHash); winners[winnerCount] = ticket.draw(nextRandom); } // yield prize is split up among all winners uint256 prizeShare = prize.div(winners.length); if (prizeShare > 0) { for (uint i = 0; i < winners.length; i++) { _awardTickets(winners[i], prizeShare); } } if (splitExternalErc20Awards) { address currentToken = externalErc20s.start(); while (currentToken != address(0) && currentToken != externalErc20s.end()) { uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool)); uint256 split = balance.div(__numberOfWinners); if (split > 0) { for (uint256 i = 0; i < winners.length; i++) { prizePool.awardExternalERC20(winners[i], currentToken, split); } } currentToken = externalErc20s.next(currentToken); } } else { _awardExternalErc20s(mainWinner); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@nomiclabs/buidler/console.sol"; import "./CompoundPrizePoolBuilder.sol"; import "./VaultPrizePoolBuilder.sol"; import "./StakePrizePoolBuilder.sol"; import "./MultipleWinnersBuilder.sol"; contract PoolWithMultipleWinnersBuilder { using SafeCastUpgradeable for uint256; event CompoundPrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy); event StakePrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy); event VaultPrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy); CompoundPrizePoolBuilder public compoundPrizePoolBuilder; VaultPrizePoolBuilder public vaultPrizePoolBuilder; StakePrizePoolBuilder public stakePrizePoolBuilder; MultipleWinnersBuilder public multipleWinnersBuilder; constructor ( CompoundPrizePoolBuilder _compoundPrizePoolBuilder, VaultPrizePoolBuilder _vaultPrizePoolBuilder, StakePrizePoolBuilder _stakePrizePoolBuilder, MultipleWinnersBuilder _multipleWinnersBuilder ) public { require(address(_compoundPrizePoolBuilder) != address(0), "GlobalBuilder/compoundPrizePoolBuilder-not-zero"); require(address(_vaultPrizePoolBuilder) != address(0), "GlobalBuilder/vaultPrizePoolBuilder-not-zero"); require(address(_stakePrizePoolBuilder) != address(0), "GlobalBuilder/stakePrizePoolBuilder-not-zero"); require(address(_multipleWinnersBuilder) != address(0), "GlobalBuilder/multipleWinnersBuilder-not-zero"); compoundPrizePoolBuilder = _compoundPrizePoolBuilder; vaultPrizePoolBuilder = _vaultPrizePoolBuilder; stakePrizePoolBuilder = _stakePrizePoolBuilder; multipleWinnersBuilder = _multipleWinnersBuilder; } function createCompoundMultipleWinners( CompoundPrizePoolBuilder.CompoundPrizePoolConfig memory prizePoolConfig, MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals ) external returns (CompoundPrizePool) { CompoundPrizePool prizePool = compoundPrizePoolBuilder.createCompoundPrizePool(prizePoolConfig); MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals); emit CompoundPrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy)); return prizePool; } function createStakeMultipleWinners( StakePrizePoolBuilder.StakePrizePoolConfig memory prizePoolConfig, MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals ) external returns (StakePrizePool) { StakePrizePool prizePool = stakePrizePoolBuilder.createStakePrizePool(prizePoolConfig); MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals); emit StakePrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy)); return prizePool; } function createVaultMultipleWinners( VaultPrizePoolBuilder.VaultPrizePoolConfig memory prizePoolConfig, MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals ) external returns (yVaultPrizePool) { yVaultPrizePool prizePool = vaultPrizePoolBuilder.createVaultPrizePool(prizePoolConfig); MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals); emit VaultPrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy)); return prizePool; } function _createMultipleWinnersAndTransferPrizePool( PrizePool prizePool, MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals ) internal returns (MultipleWinners) { MultipleWinners periodicPrizeStrategy = multipleWinnersBuilder.createMultipleWinners( prizePool, prizeStrategyConfig, decimals, msg.sender ); address ticket = address(periodicPrizeStrategy.ticket()); prizePool.setPrizeStrategy(periodicPrizeStrategy); prizePool.addControlledToken(Ticket(ticket)); prizePool.addControlledToken(ControlledTokenInterface(address(periodicPrizeStrategy.sponsorship()))); prizePool.setCreditPlanOf( ticket, prizeStrategyConfig.ticketCreditRateMantissa.toUint128(), prizeStrategyConfig.ticketCreditLimitMantissa.toUint128() ); prizePool.transferOwnership(msg.sender); return periodicPrizeStrategy; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../registry/RegistryInterface.sol"; import "./PrizePoolBuilder.sol"; import "../prize-pool/yearn/yVaultPrizePoolProxyFactory.sol"; import "../external/yearn/yVaultInterface.sol"; import "../external/openzeppelin/OpenZeppelinProxyFactoryInterface.sol"; /* solium-disable security/no-block-members */ contract VaultPrizePoolBuilder is PrizePoolBuilder { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; struct VaultPrizePoolConfig { yVaultInterface vault; uint256 reserveRateMantissa; uint256 maxExitFeeMantissa; uint256 maxTimelockDuration; } RegistryInterface public reserveRegistry; yVaultPrizePoolProxyFactory public vaultPrizePoolProxyFactory; constructor ( RegistryInterface _reserveRegistry, yVaultPrizePoolProxyFactory _vaultPrizePoolProxyFactory ) public { require(address(_reserveRegistry) != address(0), "VaultPrizePoolBuilder/reserveRegistry-not-zero"); require(address(_vaultPrizePoolProxyFactory) != address(0), "VaultPrizePoolBuilder/compound-prize-pool-builder-not-zero"); reserveRegistry = _reserveRegistry; vaultPrizePoolProxyFactory = _vaultPrizePoolProxyFactory; } function createVaultPrizePool( VaultPrizePoolConfig calldata config ) external returns (yVaultPrizePool) { yVaultPrizePool prizePool = vaultPrizePoolProxyFactory.create(); ControlledTokenInterface[] memory tokens; prizePool.initialize( reserveRegistry, tokens, config.maxExitFeeMantissa, config.maxTimelockDuration, config.vault, config.reserveRateMantissa ); prizePool.transferOwnership(msg.sender); emit PrizePoolCreated(msg.sender, address(prizePool)); return prizePool; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./yVaultPrizePool.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title yVault Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new yVault Prize Pools contract yVaultPrizePoolProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools yVaultPrizePool public instance; /// @notice Initializes the Factory with an instance of the yVault Prize Pool constructor () public { instance = new yVaultPrizePool(); } /// @notice Creates a new yVault Prize Pool as a proxy of the template instance /// @return A reference to the new proxied yVault Prize Pool function create() external returns (yVaultPrizePool) { return yVaultPrizePool(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../../external/yearn/yVaultInterface.sol"; import "../PrizePool.sol"; /// @title Prize Pool for yEarn's yVaults contract yVaultPrizePool is PrizePool { using SafeMathUpgradeable for uint256; event yVaultPrizePoolInitialized(address indexed vault); event ReserveRateMantissaSet(uint256 reserveRateMantissa); /// @notice Interface for the yEarn yVault yVaultInterface public vault; /// Amount that is never exposed to the prize uint256 public reserveRateMantissa; /// @notice Initializes the Prize Pool and Yield Service with the required contract connections /// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool /// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount /// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be /// @param _vault Address of the yEarn yVaultInterface function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration, yVaultInterface _vault, uint256 _reserveRateMantissa ) public initializer { PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa, _maxTimelockDuration ); vault = _vault; _setReserveRateMantissa(_reserveRateMantissa); emit yVaultPrizePoolInitialized(address(vault)); } function setReserveRateMantissa(uint256 _reserveRateMantissa) external onlyOwner { _setReserveRateMantissa(_reserveRateMantissa); } function _setReserveRateMantissa(uint256 _reserveRateMantissa) internal { require(_reserveRateMantissa < 1 ether, "yVaultPrizePool/reserve-rate-lt-one"); reserveRateMantissa = _reserveRateMantissa; emit ReserveRateMantissaSet(reserveRateMantissa); } /// @dev Gets the balance of the underlying assets held by the Yield Service /// @return The underlying balance of asset tokens function _balance() internal override returns (uint256) { uint256 total = _sharesToToken(vault.balanceOf(address(this))); uint256 reserve = FixedPoint.multiplyUintByMantissa(total, reserveRateMantissa); return total.sub(reserve); } /// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens /// to be held in escrow by the Yield Service function _supply(uint256) internal override { IERC20Upgradeable assetToken = _token(); uint256 total = assetToken.balanceOf(address(this)); assetToken.approve(address(vault), total); vault.deposit(total); } /// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens /// to be held in escrow by the Yield Service function _supplySpecific(uint256 amount) internal { _token().approve(address(vault), amount); vault.deposit(amount); } /// @dev The external token cannot be yDai or Dai /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal override view returns (bool) { return _externalToken != address(vault) && _externalToken != address(vault.token()); } /// @dev Allows a user to redeem yield-bearing tokens in exchange for the underlying /// asset tokens held in escrow by the Yield Service /// @param amount The amount of underlying tokens to be redeemed /// @return The actual amount of tokens transferred function _redeem(uint256 amount) internal override returns (uint256) { IERC20Upgradeable token = _token(); require(_balance() >= amount, "yVaultPrizePool/insuff-liquidity"); // yVault will try to over-withdraw so that amount is always available // we want: amount = X - X*feeRate // amount = X(1 - feeRate) // amount / (1 - feeRate) = X // calculate possible fee uint256 withdrawal; if (reserveRateMantissa > 0) { withdrawal = FixedPoint.divideUintByMantissa(amount, uint256(1e18).sub(reserveRateMantissa)); } else { withdrawal = amount; } uint256 sharesToWithdraw = _tokenToShares(withdrawal); uint256 preBalance = token.balanceOf(address(this)); vault.withdraw(sharesToWithdraw); uint256 postBalance = token.balanceOf(address(this)); uint256 amountWithdrawn = postBalance.sub(preBalance); uint256 amountRedeemable = (amountWithdrawn < amount) ? amountWithdrawn : amount; // Redeposit any asset funds that were removed preemptively for fees if (postBalance > amountRedeemable) { _supplySpecific(postBalance.sub(amountRedeemable)); } return amountRedeemable; } function _tokenToShares(uint256 tokens) internal view returns (uint256) { /** ex. rate = tokens / shares => shares = shares_total * (tokens / tokens total) */ return vault.totalSupply().mul(tokens).div(vault.balance()); } function _sharesToToken(uint256 shares) internal view returns (uint256) { uint256 ts = vault.totalSupply(); if (ts == 0 || shares == 0) { return 0; } return (vault.balance().mul(shares)).div(ts); } /// @dev Gets the underlying asset token used by the Yield Service /// @return A reference to the interface of the underling asset token function _token() internal override view returns (IERC20Upgradeable) { return IERC20Upgradeable(vault.token()); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface yVaultInterface is IERC20Upgradeable { function token() external view returns (IERC20Upgradeable); function balance() external view returns (uint256); function deposit(uint256 _amount) external; function withdraw(uint256 _shares) external; function getPricePerFullShare() external view returns (uint256); } pragma solidity >=0.6.0 <0.7.0; interface OpenZeppelinProxyFactoryInterface { function deploy(uint256 _salt, address _logic, address _admin, bytes calldata _data) external returns (address); function getDeploymentAddress(uint256 _salt, address _sender) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "./PrizePoolBuilder.sol"; import "../registry/RegistryInterface.sol"; import "../builders/MultipleWinnersBuilder.sol"; import "../prize-pool/stake/StakePrizePoolProxyFactory.sol"; /* solium-disable security/no-block-members */ contract StakePrizePoolBuilder is PrizePoolBuilder { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; struct StakePrizePoolConfig { IERC20Upgradeable token; uint256 maxExitFeeMantissa; uint256 maxTimelockDuration; } RegistryInterface public reserveRegistry; StakePrizePoolProxyFactory public stakePrizePoolProxyFactory; constructor ( RegistryInterface _reserveRegistry, StakePrizePoolProxyFactory _stakePrizePoolProxyFactory ) public { require(address(_reserveRegistry) != address(0), "StakePrizePoolBuilder/reserveRegistry-not-zero"); require(address(_stakePrizePoolProxyFactory) != address(0), "StakePrizePoolBuilder/stake-prize-pool-proxy-factory-not-zero"); reserveRegistry = _reserveRegistry; stakePrizePoolProxyFactory = _stakePrizePoolProxyFactory; } function createStakePrizePool( StakePrizePoolConfig calldata config ) external returns (StakePrizePool) { StakePrizePool prizePool = stakePrizePoolProxyFactory.create(); ControlledTokenInterface[] memory tokens; prizePool.initialize( reserveRegistry, tokens, config.maxExitFeeMantissa, config.maxTimelockDuration, config.token ); prizePool.transferOwnership(msg.sender); emit PrizePoolCreated(msg.sender, address(prizePool)); return prizePool; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./StakePrizePool.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title Stake Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new yVault Prize Pools contract StakePrizePoolProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools StakePrizePool public instance; /// @notice Initializes the Factory with an instance of the yVault Prize Pool constructor () public { instance = new StakePrizePool(); } /// @notice Creates a new Stake Prize Pool as a proxy of the template instance /// @return A reference to the new proxied Stake Prize Pool function create() external returns (StakePrizePool) { return StakePrizePool(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../PrizePool.sol"; contract StakePrizePool is PrizePool { IERC20Upgradeable private stakeToken; event StakePrizePoolInitialized(address indexed stakeToken); /// @notice Initializes the Prize Pool and Yield Service with the required contract connections /// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool /// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount /// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be /// @param _stakeToken Address of the stake token function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration, IERC20Upgradeable _stakeToken ) public initializer { PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa, _maxTimelockDuration ); stakeToken = _stakeToken; emit StakePrizePoolInitialized(address(stakeToken)); } /// @notice Determines whether the passed token can be transferred out as an external award. /// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The /// prize strategy should not be allowed to move those tokens. /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal override view returns (bool) { return address(stakeToken) != _externalToken; } /// @notice Returns the total balance (in asset tokens). This includes the deposits and interest. /// @return The underlying balance of asset tokens function _balance() internal override returns (uint256) { return stakeToken.balanceOf(address(this)); } function _token() internal override view returns (IERC20Upgradeable) { return stakeToken; } /// @notice Supplies asset tokens to the yield source. /// @param mintAmount The amount of asset tokens to be supplied function _supply(uint256 mintAmount) internal override { // no-op because nothing else needs to be done } /// @notice Redeems asset tokens from the yield source. /// @param redeemAmount The amount of yield-bearing tokens to be redeemed /// @return The actual amount of tokens that were redeemed. function _redeem(uint256 redeemAmount) internal override returns (uint256) { return redeemAmount; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "../utils/UInt256Array.sol"; import "./ComptrollerStorage.sol"; import "../token/TokenListener.sol"; /// @title The Comptroller disburses rewards to pool users /* solium-disable security/no-block-members */ contract Comptroller is ComptrollerStorage, TokenListener { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using UInt256Array for uint256[]; using ExtendedSafeCast for uint256; using BalanceDrip for BalanceDrip.State; using VolumeDrip for VolumeDrip.State; using BalanceDripManager for BalanceDripManager.State; using VolumeDripManager for VolumeDripManager.State; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; /// @notice Emitted when a balance drip is actived event BalanceDripActivated( address indexed source, address indexed measure, address indexed dripToken, uint256 dripRatePerSecond ); /// @notice Emitted when a balance drip is deactivated event BalanceDripDeactivated( address indexed source, address indexed measure, address indexed dripToken ); /// @notice Emitted when a balance drip rate is updated event BalanceDripRateSet( address indexed source, address indexed measure, address indexed dripToken, uint256 dripRatePerSecond ); /// @notice Emitted when a balance drip drips tokens event BalanceDripDripped( address indexed source, address indexed measure, address indexed dripToken, address user, uint256 amount ); event DripTokenDripped( address indexed dripToken, address indexed user, uint256 amount ); /// @notice Emitted when a volue drip drips tokens event VolumeDripDripped( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, address user, uint256 amount ); /// @notice Emitted when a user claims drip tokens event DripTokenClaimed( address indexed operator, address indexed dripToken, address indexed user, uint256 amount ); /// @notice Emitted when a volume drip is activated event VolumeDripActivated( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, uint256 periodSeconds, uint256 dripAmount ); event TransferredOut( address indexed token, address indexed to, uint256 amount ); /// @notice Emitted when a new volume drip period has started event VolumeDripPeriodStarted( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, uint32 period, uint256 dripAmount, uint256 endTime ); /// @notice Emitted when a volume drip period has ended event VolumeDripPeriodEnded( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, uint32 period, uint256 totalSupply, uint256 drippedTokens ); /// @notice Emitted when a volume drip is updated event VolumeDripSet( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, uint256 periodSeconds, uint256 dripAmount ); /// @notice Emitted when a volume drip is deactivated. event VolumeDripDeactivated( address indexed source, address indexed measure, address indexed dripToken, bool isReferral ); /// @notice Convenience struct used when updating drips struct UpdatePair { address source; address measure; } /// @notice Convenience struct used to retrieve balances after updating drips struct DripTokenBalance { address dripToken; uint256 balance; } /// @notice Initializes a new Comptroller. constructor () public { __Ownable_init(); } function transferOut(address token, address to, uint256 amount) external onlyOwner { IERC20Upgradeable(token).transfer(to, amount); emit TransferredOut(token, to, amount); } /// @notice Activates a balance drip. Only callable by the owner. /// @param source The balance drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose balances determines user's share of the drip rate. /// @param dripToken The token that is dripped to users. /// @param dripRatePerSecond The amount of drip tokens that are awarded each second to the total supply of measure. function activateBalanceDrip(address source, address measure, address dripToken, uint256 dripRatePerSecond) external onlyOwner { balanceDrips[source].activateDrip(measure, dripToken, dripRatePerSecond); emit BalanceDripActivated( source, measure, dripToken, dripRatePerSecond ); } /// @notice Deactivates a balance drip. Only callable by the owner. /// @param source The balance drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose balances determines user's share of the drip rate. /// @param dripToken The token that is dripped to users. /// @param prevDripToken The previous drip token in the balance drip list. If the dripToken is the first address, /// then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001 function deactivateBalanceDrip(address source, address measure, address dripToken, address prevDripToken) external onlyOwner { _deactivateBalanceDrip(source, measure, dripToken, prevDripToken); } /// @notice Deactivates a balance drip. Only callable by the owner. /// @param source The balance drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose balances determines user's share of the drip rate. /// @param dripToken The token that is dripped to users. /// @param prevDripToken The previous drip token in the balance drip list. If the dripToken is the first address, /// then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001 function _deactivateBalanceDrip(address source, address measure, address dripToken, address prevDripToken) internal { balanceDrips[source].deactivateDrip(measure, dripToken, prevDripToken, _currentTime().toUint32(), _availableDripTokenBalance(dripToken)); emit BalanceDripDeactivated(source, measure, dripToken); } /// @notice Gets a list of active balance drip tokens /// @param source The balance drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose balances determines user's share of the drip rate. /// @return An array of active Balance Drip token addresses function getActiveBalanceDripTokens(address source, address measure) external view returns (address[] memory) { return balanceDrips[source].getActiveBalanceDrips(measure); } /// @notice Returns the state of a balance drip. /// @param source The balance drip "source"; i.e. Prize Pool /// @param measure The token that measure's a users share of the drip /// @param dripToken The token that is being dripped to users /// @return dripRatePerSecond The current drip rate of the balance drip. /// @return exchangeRateMantissa The current exchange rate from measure to dripTokens /// @return timestamp The timestamp at which the balance drip was last updated. function getBalanceDrip( address source, address measure, address dripToken ) external view returns ( uint256 dripRatePerSecond, uint128 exchangeRateMantissa, uint32 timestamp ) { BalanceDrip.State storage balanceDrip = balanceDrips[source].getDrip(measure, dripToken); dripRatePerSecond = balanceDrip.dripRatePerSecond; exchangeRateMantissa = balanceDrip.exchangeRateMantissa; timestamp = balanceDrip.timestamp; } /// @notice Sets the drip rate for a balance drip. The drip rate is the number of drip tokens given to the /// entire supply of measure tokens. Only callable by the owner. /// @param source The balance drip "source"; i.e. Prize Pool /// @param measure The token to use to measure a user's share of the drip rate /// @param dripToken The token that is dripped to the user /// @param dripRatePerSecond The new drip rate per second function setBalanceDripRate(address source, address measure, address dripToken, uint256 dripRatePerSecond) external onlyOwner { balanceDrips[source].setDripRate(measure, dripToken, dripRatePerSecond, _currentTime().toUint32(), _availableDripTokenBalance(dripToken)); emit BalanceDripRateSet( source, measure, dripToken, dripRatePerSecond ); } /// @notice Activates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period. /// @param source The Prize Pool for which to bind to /// @param measure The Prize Pool controlled token whose volume should be measured /// @param dripToken The token that is being disbursed /// @param isReferral Whether this volume drip is for referrals /// @param periodSeconds The period of the volume drip, in seconds /// @param dripAmount The amount of dripTokens disbursed each period. /// @param endTime The time at which the first period ends. function activateVolumeDrip( address source, address measure, address dripToken, bool isReferral, uint32 periodSeconds, uint112 dripAmount, uint32 endTime ) external onlyOwner { uint32 period; if (isReferral) { period = referralVolumeDrips[source].activate(measure, dripToken, periodSeconds, dripAmount, endTime); } else { period = volumeDrips[source].activate(measure, dripToken, periodSeconds, dripAmount, endTime); } emit VolumeDripActivated( source, measure, dripToken, isReferral, periodSeconds, dripAmount ); emit VolumeDripPeriodStarted( source, measure, dripToken, isReferral, period, dripAmount, endTime ); } /// @notice Deactivates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period. /// @param source The Prize Pool for which to bind to /// @param measure The Prize Pool controlled token whose volume should be measured /// @param dripToken The token that is being disbursed /// @param isReferral Whether this volume drip is for referrals /// @param prevDripToken The previous drip token in the volume drip list. Is different for referrals vs non-referral volume drips. function deactivateVolumeDrip( address source, address measure, address dripToken, bool isReferral, address prevDripToken ) external onlyOwner { _deactivateVolumeDrip(source, measure, dripToken, isReferral, prevDripToken); } /// @notice Deactivates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period. /// @param source The Prize Pool for which to bind to /// @param measure The Prize Pool controlled token whose volume should be measured /// @param dripToken The token that is being disbursed /// @param isReferral Whether this volume drip is for referrals /// @param prevDripToken The previous drip token in the volume drip list. Is different for referrals vs non-referral volume drips. function _deactivateVolumeDrip( address source, address measure, address dripToken, bool isReferral, address prevDripToken ) internal { if (isReferral) { referralVolumeDrips[source].deactivate(measure, dripToken, prevDripToken); } else { volumeDrips[source].deactivate(measure, dripToken, prevDripToken); } emit VolumeDripDeactivated( source, measure, dripToken, isReferral ); } /// @notice Sets the parameters for the *next* volume drip period. The source, measure, dripToken and isReferral combined /// are used to uniquely identify a volume drip. Only callable by the owner. /// @param source The Prize Pool of the volume drip /// @param measure The token whose volume is being measured /// @param dripToken The token that is being disbursed /// @param isReferral Whether this volume drip is a referral /// @param periodSeconds The length to use for the next period /// @param dripAmount The amount of tokens to drip for the next period function setVolumeDrip( address source, address measure, address dripToken, bool isReferral, uint32 periodSeconds, uint112 dripAmount ) external onlyOwner { if (isReferral) { referralVolumeDrips[source].set(measure, dripToken, periodSeconds, dripAmount); } else { volumeDrips[source].set(measure, dripToken, periodSeconds, dripAmount); } emit VolumeDripSet( source, measure, dripToken, isReferral, periodSeconds, dripAmount ); } function getVolumeDrip( address source, address measure, address dripToken, bool isReferral ) external view returns ( uint256 periodSeconds, uint256 dripAmount, uint256 periodCount ) { VolumeDrip.State memory drip; if (isReferral) { drip = referralVolumeDrips[source].volumeDrips[measure][dripToken]; } else { drip = volumeDrips[source].volumeDrips[measure][dripToken]; } return ( drip.nextPeriodSeconds, drip.nextDripAmount, drip.periodCount ); } /// @notice Gets a list of active volume drip tokens /// @param source The volume drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose volume determines user's share of the drip rate. /// @param isReferral Whether this volume drip is a referral /// @return An array of active Volume Drip token addresses function getActiveVolumeDripTokens(address source, address measure, bool isReferral) external view returns (address[] memory) { if (isReferral) { return referralVolumeDrips[source].getActiveVolumeDrips(measure); } else { return volumeDrips[source].getActiveVolumeDrips(measure); } } function isVolumeDripActive( address source, address measure, address dripToken, bool isReferral ) external view returns (bool) { if (isReferral) { return referralVolumeDrips[source].isActive(measure, dripToken); } else { return volumeDrips[source].isActive(measure, dripToken); } } function getVolumeDripPeriod( address source, address measure, address dripToken, bool isReferral, uint16 period ) external view returns ( uint112 totalSupply, uint112 dripAmount, uint32 endTime ) { VolumeDrip.Period memory periodState; if (isReferral) { periodState = referralVolumeDrips[source].volumeDrips[measure][dripToken].periods[period]; } else { periodState = volumeDrips[source].volumeDrips[measure][dripToken].periods[period]; } return ( periodState.totalSupply, periodState.dripAmount, periodState.endTime ); } /// @notice Returns a users claimable balance of drip tokens. This is the combination of all balance and volume drips. /// @param dripToken The token that is being disbursed /// @param user The user whose balance should be checked. /// @return The claimable balance of the dripToken by the user. function balanceOfDrip(address user, address dripToken) external view returns (uint256) { return dripTokenBalances[dripToken][user]; } /// @notice Claims a drip token on behalf of a user. If the passed amount is less than or equal to the users drip balance, then /// they will be transferred that amount. Otherwise, it fails. /// @param user The user for whom to claim the drip tokens /// @param dripToken The drip token to claim /// @param amount The amount of drip token to claim function claimDrip(address user, address dripToken, uint256 amount) public { address sender = _msgSender(); dripTokenTotalSupply[dripToken] = dripTokenTotalSupply[dripToken].sub(amount); dripTokenBalances[dripToken][user] = dripTokenBalances[dripToken][user].sub(amount); require(IERC20Upgradeable(dripToken).transfer(user, amount), "Comptroller/claim-transfer-failed"); emit DripTokenClaimed(sender, dripToken, user, amount); } function claimDrips(address user, address[] memory dripTokens) public { for (uint i = 0; i < dripTokens.length; i++) { claimDrip(user, dripTokens[i], dripTokenBalances[dripTokens[i]][user]); } } function updateActiveBalanceDripsForPairs( UpdatePair[] memory pairs ) public { uint256 currentTime = _currentTime(); uint256 i; for (i = 0; i < pairs.length; i++) { UpdatePair memory pair = pairs[i]; _updateActiveBalanceDrips( balanceDrips[pair.source], pair.source, pair.measure, IERC20Upgradeable(pair.measure).totalSupply(), currentTime ); } } function updateActiveVolumeDripsForPairs( UpdatePair[] memory pairs ) public { uint256 i; for (i = 0; i < pairs.length; i++) { UpdatePair memory pair = pairs[i]; _updateActiveVolumeDrips( volumeDrips[pair.source], pair.source, pair.measure, false ); _updateActiveVolumeDrips( referralVolumeDrips[pair.source], pair.source, pair.measure, true ); } } function mintAndCaptureVolumeDripsForPairs( UpdatePair[] memory pairs, address user, uint256 amount, address[] memory dripTokens ) public { uint256 i; for (i = 0; i < pairs.length; i++) { UpdatePair memory pair = pairs[i]; _mintAndCaptureForVolumeDrips(pair.source, pair.measure, user, amount, dripTokens); _mintAndCaptureReferralVolumeDrips(pair.source, pair.measure, user, amount, dripTokens); } } function _mintAndCaptureForVolumeDrips( address source, address measure, address user, uint256 amount, address[] memory dripTokens ) internal { uint i; for (i = 0; i < dripTokens.length; i++) { address dripToken = dripTokens[i]; VolumeDrip.State storage state = volumeDrips[source].volumeDrips[measure][dripToken]; _captureClaimForVolumeDrip(state, source, measure, dripToken, false, user, amount); } } function _mintAndCaptureReferralVolumeDrips( address source, address measure, address user, uint256 amount, address[] memory dripTokens ) internal { uint i; for (i = 0; i < dripTokens.length; i++) { address dripToken = dripTokens[i]; VolumeDrip.State storage referralState = referralVolumeDrips[source].volumeDrips[measure][dripToken]; _captureClaimForVolumeDrip(referralState, source, measure, dripToken, true, user, amount); } } function _captureClaimForVolumeDrip( VolumeDrip.State storage dripState, address source, address measure, address dripToken, bool isReferral, address user, uint256 amount ) internal { uint256 newUserTokens = dripState.mint( user, amount ); if (newUserTokens > 0) { _addDripBalance(dripToken, user, newUserTokens); emit VolumeDripDripped(source, measure, dripToken, isReferral, user, newUserTokens); } } /// @param pairs The (source, measure) pairs to update. For each pair all of the balance drips, volume drips, and referral volume drips will be updated. /// @param user The user whose drips and balances will be updated. /// @param dripTokens The drip tokens to retrieve claim balances for. function captureClaimsForBalanceDripsForPairs( UpdatePair[] memory pairs, address user, address[] memory dripTokens ) public { uint256 i; for (i = 0; i < pairs.length; i++) { UpdatePair memory pair = pairs[i]; uint256 measureBalance = IERC20Upgradeable(pair.measure).balanceOf(user); _captureClaimsForBalanceDrips(pair.source, pair.measure, user, measureBalance, dripTokens); } } function _captureClaimsForBalanceDrips( address source, address measure, address user, uint256 userMeasureBalance, address[] memory dripTokens ) internal { uint i; for (i = 0; i < dripTokens.length; i++) { address dripToken = dripTokens[i]; BalanceDrip.State storage state = balanceDrips[source].balanceDrips[measure][dripToken]; if (state.exchangeRateMantissa > 0) { _captureClaimForBalanceDrip(state, source, measure, dripToken, user, userMeasureBalance); } } } function _captureClaimForBalanceDrip( BalanceDrip.State storage dripState, address source, address measure, address dripToken, address user, uint256 measureBalance ) internal { uint256 newUserTokens = dripState.captureNewTokensForUser( user, measureBalance ); if (newUserTokens > 0) { _addDripBalance(dripToken, user, newUserTokens); emit BalanceDripDripped(source, measure, dripToken, user, newUserTokens); } } function balanceOfClaims( address user, address[] memory dripTokens ) public view returns (DripTokenBalance[] memory) { DripTokenBalance[] memory balances = new DripTokenBalance[](dripTokens.length); uint256 i; for (i = 0; i < dripTokens.length; i++) { balances[i] = DripTokenBalance({ dripToken: dripTokens[i], balance: dripTokenBalances[dripTokens[i]][user] }); } return balances; } /// @notice Updates the given drips for a user and then claims the given drip tokens. This call will /// poke all of the drips and update the claim balances for the given user. /// @dev This function will be useful to check the *current* claim balances for a user. /// Just need to run this as a constant function to see the latest balances. /// in order to claim the values, this function needs to be run alongside a claimDrip function. /// @param pairs The (source, measure) pairs of drips to update for the given user /// @param user The user for whom to update and claim tokens /// @param dripTokens The drip tokens whose entire balance will be claimed after the update. /// @return The claimable balance of each of the passed drip tokens for the user. These are the post-update balances, and therefore the most accurate. function updateDrips( UpdatePair[] memory pairs, address user, address[] memory dripTokens ) public returns (DripTokenBalance[] memory) { updateActiveBalanceDripsForPairs(pairs); captureClaimsForBalanceDripsForPairs(pairs, user, dripTokens); updateActiveVolumeDripsForPairs(pairs); mintAndCaptureVolumeDripsForPairs(pairs, user, 0, dripTokens); DripTokenBalance[] memory balances = balanceOfClaims(user, dripTokens); return balances; } /// @notice Updates the given drips for a user and then claims the given drip tokens. This call will /// poke all of the drips and update the claim balances for the given user. /// @dev This function will be useful to check the *current* claim balances for a user. /// Just need to run this as a constant function to see the latest balances. /// in order to claim the values, this function needs to be run alongside a claimDrip function. /// @param pairs The (source, measure) pairs of drips to update for the given user /// @param user The user for whom to update and claim tokens /// @param dripTokens The drip tokens whose entire balance will be claimed after the update. /// @return The claimable balance of each of the passed drip tokens for the user. These are the post-update balances, and therefore the most accurate. function updateAndClaimDrips( UpdatePair[] calldata pairs, address user, address[] calldata dripTokens ) external returns (DripTokenBalance[] memory) { DripTokenBalance[] memory balances = updateDrips(pairs, user, dripTokens); claimDrips(user, dripTokens); return balances; } function _activeBalanceDripTokens(address source, address measure) internal view returns (address[] memory) { return balanceDrips[source].activeBalanceDrips[measure].addressArray(); } function _activeVolumeDripTokens(address source, address measure) internal view returns (address[] memory) { return volumeDrips[source].activeVolumeDrips[measure].addressArray(); } function _activeReferralVolumeDripTokens(address source, address measure) internal view returns (address[] memory) { return referralVolumeDrips[source].activeVolumeDrips[measure].addressArray(); } /// @notice Updates the balance drips /// @param source The Prize Pool of the balance drip /// @param manager The BalanceDripManager whose drips should be updated /// @param measure The measure token whose balance is changing /// @param measureTotalSupply The last total supply of the measure tokens /// @param currentTime The current function _updateActiveBalanceDrips( BalanceDripManager.State storage manager, address source, address measure, uint256 measureTotalSupply, uint256 currentTime ) internal { address prevDripToken = manager.activeBalanceDrips[measure].end(); address currentDripToken = manager.activeBalanceDrips[measure].start(); while (currentDripToken != address(0) && currentDripToken != manager.activeBalanceDrips[measure].end()) { BalanceDrip.State storage dripState = manager.balanceDrips[measure][currentDripToken]; uint256 limit = _availableDripTokenBalance(currentDripToken); uint256 newTokens = dripState.drip( measureTotalSupply, currentTime, limit ); // if we've hit the limit, then kill it. bool isDripComplete = newTokens == limit; if (isDripComplete) { _deactivateBalanceDrip(source, measure, currentDripToken, prevDripToken); } prevDripToken = currentDripToken; currentDripToken = manager.activeBalanceDrips[measure].next(currentDripToken); } } /// @notice Records a deposit for a volume drip /// @param source The Prize Pool of the volume drip /// @param manager The VolumeDripManager containing the drips that need to be iterated through. /// @param isReferral Whether the passed manager contains referral volume drip /// @param measure The token that was deposited function _updateActiveVolumeDrips( VolumeDripManager.State storage manager, address source, address measure, bool isReferral ) internal { address prevDripToken = manager.activeVolumeDrips[measure].end(); uint256 currentTime = _currentTime(); address currentDripToken = manager.activeVolumeDrips[measure].start(); while (currentDripToken != address(0) && currentDripToken != manager.activeVolumeDrips[measure].end()) { VolumeDrip.State storage dripState = manager.volumeDrips[measure][currentDripToken]; uint256 limit = _availableDripTokenBalance(currentDripToken); uint32 lastPeriod = dripState.periodCount; uint256 newTokens = dripState.drip( currentTime, limit ); if (lastPeriod != dripState.periodCount) { emit VolumeDripPeriodEnded( source, measure, currentDripToken, isReferral, lastPeriod, dripState.periods[lastPeriod].totalSupply, newTokens ); emit VolumeDripPeriodStarted( source, measure, currentDripToken, isReferral, dripState.periodCount, dripState.periods[dripState.periodCount].dripAmount, dripState.periods[dripState.periodCount].endTime ); } // if we've hit the limit, then kill it. bool isDripComplete = newTokens == limit; if (isDripComplete) { _deactivateVolumeDrip(source, measure, currentDripToken, isReferral, prevDripToken); } prevDripToken = currentDripToken; currentDripToken = manager.activeVolumeDrips[measure].next(currentDripToken); } } function _addDripBalance(address dripToken, address user, uint256 amount) internal returns (uint256) { uint256 amountAvailable = _availableDripTokenBalance(dripToken); uint256 actualAmount = (amount > amountAvailable) ? amountAvailable : amount; dripTokenTotalSupply[dripToken] = dripTokenTotalSupply[dripToken].add(actualAmount); dripTokenBalances[dripToken][user] = dripTokenBalances[dripToken][user].add(actualAmount); emit DripTokenDripped(dripToken, user, actualAmount); return actualAmount; } function _availableDripTokenBalance(address dripToken) internal view returns (uint256) { uint256 comptrollerBalance = IERC20Upgradeable(dripToken).balanceOf(address(this)); uint256 totalClaimable = dripTokenTotalSupply[dripToken]; return (totalClaimable < comptrollerBalance) ? comptrollerBalance.sub(totalClaimable) : 0; } /// @notice Called by a "source" (i.e. Prize Pool) when a user mints new "measure" tokens. /// @param to The user who is minting the tokens /// @param amount The amount of tokens they are minting /// @param measure The measure token they are minting /// @param referrer The user who referred the minting. function beforeTokenMint( address to, uint256 amount, address measure, address referrer ) external override { address source = _msgSender(); uint256 balance = IERC20Upgradeable(measure).balanceOf(to); uint256 totalSupply = IERC20Upgradeable(measure).totalSupply(); address[] memory balanceDripTokens = _activeBalanceDripTokens(source, measure); _updateActiveBalanceDrips( balanceDrips[source], source, measure, totalSupply, _currentTime() ); _captureClaimsForBalanceDrips(source, measure, to, balance, balanceDripTokens); address[] memory volumeDripTokens = _activeVolumeDripTokens(source, measure); _updateActiveVolumeDrips( volumeDrips[source], source, measure, false ); _mintAndCaptureForVolumeDrips(source, measure, to, amount, volumeDripTokens); if (referrer != address(0)) { address[] memory referralVolumeDripTokens = _activeReferralVolumeDripTokens(source, measure); _updateActiveVolumeDrips( referralVolumeDrips[source], source, measure, true ); _mintAndCaptureReferralVolumeDrips(source, measure, referrer, amount, referralVolumeDripTokens); } } /// @notice Called by a "source" (i.e. Prize Pool) when tokens change hands or are burned /// @param from The user who is sending the tokens /// @param to The user who is receiving the tokens /// @param measure The measure token they are burning function beforeTokenTransfer( address from, address to, uint256, address measure ) external override { if (from == address(0)) { // ignore minting return; } address source = _msgSender(); uint256 totalSupply = IERC20Upgradeable(measure).totalSupply(); uint256 fromBalance = IERC20Upgradeable(measure).balanceOf(from); address[] memory balanceDripTokens = _activeBalanceDripTokens(source, measure); _updateActiveBalanceDrips( balanceDrips[source], source, measure, totalSupply, _currentTime() ); _captureClaimsForBalanceDrips(source, measure, from, fromBalance, balanceDripTokens); if (to != address(0)) { uint256 toBalance = IERC20Upgradeable(measure).balanceOf(to); _captureClaimsForBalanceDrips(source, measure, to, toBalance, balanceDripTokens); } } /// @notice returns the current time. Allows for override in testing. /// @return The current time (block.timestamp) function _currentTime() internal virtual view returns (uint256) { return block.timestamp; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; library UInt256Array { function remove(uint256[] storage self, uint256 index) internal { require(index < self.length, "UInt256Array/unknown-index"); self[index] = self[self.length-1]; delete self[self.length-1]; self.pop(); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../drip/BalanceDripManager.sol"; import "../drip/VolumeDripManager.sol"; contract ComptrollerStorage is OwnableUpgradeable { mapping(address => VolumeDripManager.State) internal volumeDrips; mapping(address => VolumeDripManager.State) internal referralVolumeDrips; mapping(address => BalanceDripManager.State) internal balanceDrips; mapping(address => uint256) internal dripTokenTotalSupply; mapping(address => mapping(address => uint256)) internal dripTokenBalances; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../utils/MappedSinglyLinkedList.sol"; import "./BalanceDrip.sol"; /// @title Manages the lifecycle of a set of Balance Drips. library BalanceDripManager { using SafeMathUpgradeable for uint256; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using BalanceDrip for BalanceDrip.State; struct State { mapping(address => MappedSinglyLinkedList.Mapping) activeBalanceDrips; mapping(address => mapping(address => BalanceDrip.State)) balanceDrips; } /// @notice Activates a drip by setting it's state and adding it to the active balance drips list. /// @param self The BalanceDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param dripRatePerSecond The amount of the drip token to be dripped per second function activateDrip( State storage self, address measure, address dripToken, uint256 dripRatePerSecond ) internal { require(!self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-active"); if (self.activeBalanceDrips[measure].count == 0) { self.activeBalanceDrips[measure].initialize(); } self.activeBalanceDrips[measure].addAddress(dripToken); self.balanceDrips[measure][dripToken].resetTotalDripped(); self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond; } /// @notice Deactivates an active balance drip. The balance drip is removed from the active balance drips list. /// The drip rate for the balance drip will be set to zero to ensure it's "frozen". /// @param measure The measure token /// @param dripToken The drip token /// @param prevDripToken The previous drip token previous in the list. /// If no previous, then pass the SENTINEL address: 0x0000000000000000000000000000000000000001 /// @param currentTime The current time function deactivateDrip( State storage self, address measure, address dripToken, address prevDripToken, uint32 currentTime, uint256 maxNewTokens ) internal { self.activeBalanceDrips[measure].removeAddress(prevDripToken, dripToken); self.balanceDrips[measure][dripToken].drip(IERC20Upgradeable(measure).totalSupply(), currentTime, maxNewTokens); self.balanceDrips[measure][dripToken].dripRatePerSecond = 0; } /// @notice Gets a list of active balance drip tokens /// @param self The BalanceDripManager state /// @param measure The measure token /// @return An array of Balance Drip token addresses function getActiveBalanceDrips(State storage self, address measure) internal view returns (address[] memory) { return self.activeBalanceDrips[measure].addressArray(); } /// @notice Sets the drip rate for an active balance drip. /// @param self The BalanceDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param dripRatePerSecond The amount to drip of the token each second /// @param currentTime The current time. function setDripRate( State storage self, address measure, address dripToken, uint256 dripRatePerSecond, uint32 currentTime, uint256 maxNewTokens ) internal { require(self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-not-active"); self.balanceDrips[measure][dripToken].drip(IERC20Upgradeable(measure).totalSupply(), currentTime, maxNewTokens); self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond; } /// @notice Returns whether or not a drip is active for the given measure, dripToken pair /// @param self The BalanceDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @return True if there is an active balance drip for the pair, false otherwise function isDripActive(State storage self, address measure, address dripToken) internal view returns (bool) { return self.activeBalanceDrips[measure].contains(dripToken); } /// @notice Returns the BalanceDrip.State for the given measure, dripToken pair /// @param self The BalanceDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @return The BalanceDrip.State for the pair function getDrip(State storage self, address measure, address dripToken) internal view returns (BalanceDrip.State storage) { return self.balanceDrips[measure][dripToken]; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "../utils/ExtendedSafeCast.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; /// @title Calculates a users share of a token faucet. /// @notice The tokens are dripped at a "drip rate per second". This is the number of tokens that /// are dripped each second to the entire supply of a "measure" token. A user's share of ownership /// of the measure token corresponds to the share of the drip tokens per second. library BalanceDrip { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using ExtendedSafeCast for uint256; struct UserState { uint128 lastExchangeRateMantissa; } struct State { uint256 dripRatePerSecond; uint112 exchangeRateMantissa; uint112 totalDripped; uint32 timestamp; mapping(address => UserState) userStates; } /// @notice Captures new tokens for a user /// @dev This must be called before changes to the user's balance (i.e. before mint, transfer or burns) /// @param self The balance drip state /// @param user The user to capture tokens for /// @param userMeasureBalance The current balance of the user's measure tokens /// @return The number of new tokens function captureNewTokensForUser( State storage self, address user, uint256 userMeasureBalance ) internal returns (uint128) { return _captureNewTokensForUser( self, user, userMeasureBalance ); } function resetTotalDripped(State storage self) internal { self.totalDripped = 0; } /// @notice Drips new tokens. /// @dev Should be called immediately before a change to the measure token's total supply /// @param self The balance drip state /// @param measureTotalSupply The measure token's last total supply (prior to any change) /// @param timestamp The current time /// @param maxNewTokens Maximum new tokens that can be dripped /// @return The number of new tokens dripped. function drip( State storage self, uint256 measureTotalSupply, uint256 timestamp, uint256 maxNewTokens ) internal returns (uint256) { // this should only run once per block. if (self.timestamp == uint32(timestamp)) { return 0; } uint256 lastTime = self.timestamp == 0 ? timestamp : self.timestamp; uint256 newSeconds = timestamp.sub(lastTime); uint112 exchangeRateMantissa = self.exchangeRateMantissa == 0 ? FixedPoint.SCALE.toUint112() : self.exchangeRateMantissa; uint256 newTokens; if (newSeconds > 0 && self.dripRatePerSecond > 0) { newTokens = newSeconds.mul(self.dripRatePerSecond); if (newTokens > maxNewTokens) { newTokens = maxNewTokens; } uint256 indexDeltaMantissa = measureTotalSupply > 0 ? FixedPoint.calculateMantissa(newTokens, measureTotalSupply) : 0; exchangeRateMantissa = uint256(exchangeRateMantissa).add(indexDeltaMantissa).toUint112(); } self.exchangeRateMantissa = exchangeRateMantissa; self.totalDripped = uint256(self.totalDripped).add(newTokens).toUint112(); self.timestamp = timestamp.toUint32(); return newTokens; } function _captureNewTokensForUser( State storage self, address user, uint256 userMeasureBalance ) private returns (uint128) { UserState storage userState = self.userStates[user]; uint256 lastExchangeRateMantissa = userState.lastExchangeRateMantissa; if (lastExchangeRateMantissa == 0) { // if the index is not intialized lastExchangeRateMantissa = FixedPoint.SCALE.toUint112(); } uint256 deltaExchangeRateMantissa = uint256(self.exchangeRateMantissa).sub(lastExchangeRateMantissa); uint128 newTokens = FixedPoint.multiplyUintByMantissa(userMeasureBalance, deltaExchangeRateMantissa).toUint128(); self.userStates[user] = UserState({ lastExchangeRateMantissa: self.exchangeRateMantissa }); return newTokens; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; library ExtendedSafeCast { /** * @dev Converts an unsigned uint256 into a unsigned uint112. * * Requirements: * * - input must be less than or equal to maxUint112. */ function toUint112(uint256 value) internal pure returns (uint112) { require(value < 2**112, "SafeCast: value doesn't fit in an uint112"); return uint112(value); } /** * @dev Converts an unsigned uint256 into a unsigned uint96. * * Requirements: * * - input must be less than or equal to maxUint96. */ function toUint96(uint256 value) internal pure returns (uint96) { require(value < 2**96, "SafeCast: value doesn't fit in an uint96"); return uint96(value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../utils/MappedSinglyLinkedList.sol"; import "./VolumeDrip.sol"; /// @title Manages the active set of Volume Drips. library VolumeDripManager { using SafeMathUpgradeable for uint256; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using VolumeDrip for VolumeDrip.State; struct State { mapping(address => MappedSinglyLinkedList.Mapping) activeVolumeDrips; mapping(address => mapping(address => VolumeDrip.State)) volumeDrips; } /// @notice Activates a volume drip for the given (measure,dripToken) pair. /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param periodSeconds The period of the volume drip in seconds /// @param dripAmount The amount of tokens to drip each period /// @param endTime The end time to set for the current period. function activate( State storage self, address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount, uint32 endTime ) internal returns (uint32) { require(!self.activeVolumeDrips[measure].contains(dripToken), "VolumeDripManager/drip-active"); if (self.activeVolumeDrips[measure].count == 0) { self.activeVolumeDrips[measure].initialize(); } self.activeVolumeDrips[measure].addAddress(dripToken); self.volumeDrips[measure][dripToken].setNewPeriod(periodSeconds, dripAmount, endTime); return self.volumeDrips[measure][dripToken].periodCount; } /// @notice Deactivates the volume drip for the given (measure, dripToken) pair. /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param prevDripToken The active drip token previous to the passed on in the list. function deactivate( State storage self, address measure, address dripToken, address prevDripToken ) internal { self.activeVolumeDrips[measure].removeAddress(prevDripToken, dripToken); } /// @notice Gets a list of active balance drip tokens /// @param self The BalanceDripManager state /// @param measure The measure token /// @return An array of Balance Drip token addresses function getActiveVolumeDrips(State storage self, address measure) internal view returns (address[] memory) { return self.activeVolumeDrips[measure].addressArray(); } /// @notice Sets the parameters for the next period of an active volume drip /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param periodSeconds The length in seconds to use for the next period /// @param dripAmount The amount of tokens to be dripped in the next period function set(State storage self, address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount) internal { require(self.activeVolumeDrips[measure].contains(dripToken), "VolumeDripManager/drip-not-active"); self.volumeDrips[measure][dripToken].setNextPeriod(periodSeconds, dripAmount); } /// @notice Returns whether or not an active volume drip exists for the given (measure, dripToken) pair /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token function isActive(State storage self, address measure, address dripToken) internal view returns (bool) { return self.activeVolumeDrips[measure].contains(dripToken); } /// @notice Returns the VolumeDrip.State for the given (measure, dripToken) pair. /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token function getDrip(State storage self, address measure, address dripToken) internal view returns (VolumeDrip.State storage) { return self.volumeDrips[measure][dripToken]; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../utils/ExtendedSafeCast.sol"; library VolumeDrip { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using ExtendedSafeCast for uint256; struct Deposit { uint112 balance; uint32 period; } struct Period { uint112 totalSupply; uint112 dripAmount; uint32 endTime; } struct State { mapping(address => Deposit) deposits; mapping(uint32 => Period) periods; uint32 nextPeriodSeconds; uint112 nextDripAmount; uint112 __gap; uint112 totalDripped; uint32 periodCount; } function setNewPeriod( State storage self, uint32 _periodSeconds, uint112 dripAmount, uint32 endTime ) internal minPeriod(_periodSeconds) { self.nextPeriodSeconds = _periodSeconds; self.nextDripAmount = dripAmount; self.totalDripped = 0; self.periodCount = uint256(self.periodCount).add(1).toUint16(); self.periods[self.periodCount] = Period({ totalSupply: 0, dripAmount: dripAmount, endTime: endTime }); } function setNextPeriod( State storage self, uint32 _periodSeconds, uint112 dripAmount ) internal minPeriod(_periodSeconds) { self.nextPeriodSeconds = _periodSeconds; self.nextDripAmount = dripAmount; } function drip( State storage self, uint256 currentTime, uint256 maxNewTokens ) internal returns (uint256) { if (_isPeriodOver(self, currentTime)) { return _completePeriod(self, currentTime, maxNewTokens); } return 0; } function mint( State storage self, address user, uint256 amount ) internal returns (uint256) { if (self.periodCount == 0) { return 0; } uint256 accrued = _lastBalanceAccruedAmount(self, self.deposits[user].period, self.deposits[user].balance); uint32 currentPeriod = self.periodCount; if (accrued > 0) { self.deposits[user] = Deposit({ balance: amount.toUint112(), period: currentPeriod }); } else { self.deposits[user] = Deposit({ balance: uint256(self.deposits[user].balance).add(amount).toUint112(), period: currentPeriod }); } self.periods[currentPeriod].totalSupply = uint256(self.periods[currentPeriod].totalSupply).add(amount).toUint112(); return accrued; } function currentPeriod(State storage self) internal view returns (Period memory) { return self.periods[self.periodCount]; } function _isPeriodOver(State storage self, uint256 currentTime) private view returns (bool) { return currentTime >= self.periods[self.periodCount].endTime; } function _completePeriod( State storage self, uint256 currentTime, uint256 maxNewTokens ) private onlyPeriodOver(self, currentTime) returns (uint256) { // calculate the actual drip amount uint112 dripAmount; // If no one deposited, then don't drip anything if (self.periods[self.periodCount].totalSupply > 0) { dripAmount = self.periods[self.periodCount].dripAmount; } // if the drip amount is not valid, it has to be updated. if (dripAmount > maxNewTokens) { dripAmount = maxNewTokens.toUint112(); self.periods[self.periodCount].dripAmount = dripAmount; } // if we are completing the period far into the future, then we'll have skipped a lot of periods. // Here we set the end time so that it's the next period from *now* uint256 lastEndTime = self.periods[self.periodCount].endTime; uint256 numberOfPeriods = currentTime.sub(lastEndTime).div(self.nextPeriodSeconds).add(1); uint256 endTime = lastEndTime.add(numberOfPeriods.mul(self.nextPeriodSeconds)); self.totalDripped = uint256(self.totalDripped).add(dripAmount).toUint112(); self.periodCount = uint256(self.periodCount).add(1).toUint16(); self.periods[self.periodCount] = Period({ totalSupply: 0, dripAmount: self.nextDripAmount, endTime: endTime.toUint32() }); return dripAmount; } function _lastBalanceAccruedAmount( State storage self, uint32 depositPeriod, uint128 balance ) private view returns (uint256) { uint256 accrued; if (depositPeriod < self.periodCount && self.periods[depositPeriod].totalSupply > 0) { uint256 fractionMantissa = FixedPoint.calculateMantissa(balance, self.periods[depositPeriod].totalSupply); accrued = FixedPoint.multiplyUintByMantissa(self.periods[depositPeriod].dripAmount, fractionMantissa); } return accrued; } modifier onlyPeriodNotOver(State storage self, uint256 _currentTime) { require(!_isPeriodOver(self, _currentTime), "VolumeDrip/period-over"); _; } modifier onlyPeriodOver(State storage self, uint256 _currentTime) { require(_isPeriodOver(self, _currentTime), "VolumeDrip/period-not-over"); _; } modifier minPeriod(uint256 _periodSeconds) { require(_periodSeconds > 0, "VolumeDrip/period-gt-zero"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface DaiInterface is IERC20Upgradeable { // --- Approve by signature --- function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function transferFrom(address src, address dst, uint wad) external override returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../external/maker/DaiInterface.sol"; import "../prize-pool/PrizePoolInterface.sol"; /// @title Allows users to approve and deposit dai into a prize pool in a single transaction. contract PermitAndDepositDai is OwnableUpgradeable { using SafeERC20Upgradeable for DaiInterface; /// @notice Permits this contract to spend on a users behalf, and deposits into the prize pool. /// @dev The Dai permit params match the Dai#permit function, but it expects the `spender` to be /// the address of this contract. /// @param holder The address spending the tokens /// @param nonce The nonce of the tx. Should be retrieved from the Dai token /// @param expiry The timestamp at which the sig expires /// @param allowed If true, then the spender is approving holder the max allowance. False makes the allowance zero. /// @param v The `v` portion of the signature. /// @param r The `r` portion of the signature. /// @param s The `s` portion of the signature. /// @param prizePool The prize pool to deposit into /// @param to The address that will receive the controlled tokens /// @param amount The amount to deposit /// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship) /// @param referrer The address that referred the deposit function permitAndDepositTo( // --- Approve by signature --- address dai, address holder, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s, address prizePool, address to, uint256 amount, address controlledToken, address referrer ) external { require(msg.sender == holder, "PermitAndDepositDai/only-signer"); DaiInterface(dai).permit(holder, address(this), nonce, expiry, allowed, v, r, s); _depositTo(dai, holder, prizePool, to, amount, controlledToken, referrer); } /// @notice Deposits into a Prize Pool from the sender. Tokens will be transferred from the sender /// then deposited into the Pool on the sender's behalf. This can be called after permitAndDepositTo is called, /// as this contract will have full approval for a user. /// @param prizePool The prize pool to deposit into /// @param to The address that will receive the controlled tokens /// @param amount The amount to deposit /// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship) /// @param referrer The address that referred the deposit function depositTo( address dai, address prizePool, address to, uint256 amount, address controlledToken, address referrer ) external { _depositTo(dai, msg.sender, prizePool, to, amount, controlledToken, referrer); } function _depositTo( address dai, address holder, address prizePool, address to, uint256 amount, address controlledToken, address referrer ) internal { DaiInterface(dai).safeTransferFrom(holder, address(this), amount); DaiInterface(dai).approve(address(prizePool), amount); PrizePoolInterface(prizePool).depositTo(to, amount, controlledToken, referrer); } } pragma solidity ^0.6.12; import "./PeriodicPrizeStrategyListenerInterface.sol"; import "./PeriodicPrizeStrategyListenerLibrary.sol"; import "../Constants.sol"; abstract contract PeriodicPrizeStrategyListener is PeriodicPrizeStrategyListenerInterface { function supportsInterface(bytes4 interfaceId) external override view returns (bool) { return ( interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 || interfaceId == PeriodicPrizeStrategyListenerLibrary.ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../PeriodicPrizeStrategy.sol"; /* solium-disable security/no-block-members */ contract SingleRandomWinner is PeriodicPrizeStrategy { event NoWinner(); function _distribute(uint256 randomNumber) internal override { uint256 prize = prizePool.captureAwardBalance(); address winner = ticket.draw(randomNumber); if (winner != address(0)) { _awardTickets(winner, prize); _awardAllExternalTokens(winner); } else { emit NoWinner(); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./SingleRandomWinner.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; contract SingleRandomWinnerProxyFactory is ProxyFactory { SingleRandomWinner public instance; constructor () public { instance = new SingleRandomWinner(); } function create() external returns (SingleRandomWinner) { return SingleRandomWinner(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./RegistryInterface.sol"; /// @title Interface that allows a user to draw an address using an index contract Registry is OwnableUpgradeable, RegistryInterface { address private pointer; event Registered(address indexed pointer); constructor () public { __Ownable_init(); } function register(address _pointer) external onlyOwner { pointer = _pointer; emit Registered(pointer); } function lookup() external override view returns (address) { return pointer; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./ReserveInterface.sol"; import "../prize-pool/PrizePoolInterface.sol"; /// @title Interface that allows a user to draw an address using an index contract Reserve is OwnableUpgradeable, ReserveInterface { event ReserveRateMantissaSet(uint256 rateMantissa); uint256 public rateMantissa; constructor () public { __Ownable_init(); } function setRateMantissa( uint256 _rateMantissa ) external onlyOwner { rateMantissa = _rateMantissa; emit ReserveRateMantissaSet(rateMantissa); } function withdrawReserve(address prizePool, address to) external onlyOwner returns (uint256) { return PrizePoolInterface(prizePool).withdrawReserve(to); } function reserveRateMantissa(address) external view override returns (uint256) { return rateMantissa; } } pragma solidity >=0.6.0 <0.7.0; import "../drip/BalanceDrip.sol"; contract BalanceDripExposed { using BalanceDrip for BalanceDrip.State; event DrippedTotalSupply( uint256 newTokens ); event Dripped( address indexed user, uint256 newTokens ); BalanceDrip.State internal dripState; function setDripRate( uint256 dripRatePerSecond ) external { dripState.dripRatePerSecond = dripRatePerSecond; } function drip( uint256 measureTotalSupply, uint256 currentTime, uint256 maxNewTokens ) external returns (uint256) { uint256 newTokens = dripState.drip( measureTotalSupply, currentTime, maxNewTokens ); emit DrippedTotalSupply(newTokens); return newTokens; } function captureNewTokensForUser( address user, uint256 userMeasureBalance ) external returns (uint128) { uint128 newTokens = dripState.captureNewTokensForUser( user, userMeasureBalance ); emit Dripped(user, newTokens); return newTokens; } function dripTwice( uint256 measureTotalSupply, uint256 currentTime, uint256 maxNewTokens ) external returns (uint256) { uint256 newTokens = dripState.drip( measureTotalSupply, currentTime, maxNewTokens ); newTokens = newTokens + dripState.drip( measureTotalSupply, currentTime, maxNewTokens ); emit DrippedTotalSupply(newTokens); return newTokens; } function exchangeRateMantissa() external view returns (uint256) { return dripState.exchangeRateMantissa; } function totalDripped() external view returns (uint256) { return dripState.totalDripped; } function resetTotalDripped() external { dripState.resetTotalDripped(); } } pragma solidity >=0.6.0 <0.7.0; import "../drip/BalanceDripManager.sol"; contract BalanceDripManagerExposed { using BalanceDripManager for BalanceDripManager.State; BalanceDripManager.State dripManager; function activateDrip(address measure, address dripToken, uint256 dripRatePerSecond) external { dripManager.activateDrip(measure, dripToken, dripRatePerSecond); } function deactivateDrip(address measure, address prevDripToken, address dripToken, uint32 currentTime, uint256 maxNewTokens) external { dripManager.deactivateDrip(measure, prevDripToken, dripToken, currentTime, maxNewTokens); } function isDripActive(address measure, address dripToken) external view returns (bool) { return dripManager.isDripActive(measure, dripToken); } function setDripRate(address measure, address dripToken, uint256 dripRatePerSecond, uint32 currentTime, uint256 maxNewTokens) external { dripManager.setDripRate(measure, dripToken, dripRatePerSecond, currentTime, maxNewTokens); } function getActiveBalanceDrips(address measure) external view returns (address[] memory) { return dripManager.getActiveBalanceDrips(measure); } function getDrip( address measure, address dripToken ) external view returns ( uint256 dripRatePerSecond, uint128 exchangeRateMantissa, uint32 timestamp ) { BalanceDrip.State storage dripState = dripManager.getDrip(measure, dripToken); dripRatePerSecond = dripState.dripRatePerSecond; exchangeRateMantissa = dripState.exchangeRateMantissa; timestamp = dripState.timestamp; } } pragma solidity >=0.6.0 <0.7.0; import "../prize-pool/compound/CompoundPrizePool.sol"; /* solium-disable security/no-block-members */ contract CompoundPrizePoolHarness is CompoundPrizePool { uint256 public currentTime; function setCurrentTime(uint256 _currentTime) external { currentTime = _currentTime; } function setTimelockBalance(uint256 _timelockBalance) external { timelockTotalSupply = _timelockBalance; } function _currentTime() internal override view returns (uint256) { return currentTime; } function supply(uint256 mintAmount) external { _supply(mintAmount); } function redeem(uint256 redeemAmount) external returns (uint256) { return _redeem(redeemAmount); } } pragma solidity >=0.6.0 <0.7.0; import "./CompoundPrizePoolHarness.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Compound Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new Compound Prize Pools contract CompoundPrizePoolHarnessProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools CompoundPrizePoolHarness public instance; /// @notice Initializes the Factory with an instance of the Compound Prize Pool constructor () public { instance = new CompoundPrizePoolHarness(); } /// @notice Creates a new Compound Prize Pool as a proxy of the template instance /// @return A reference to the new proxied Compound Prize Pool function create() external returns (CompoundPrizePoolHarness) { return CompoundPrizePoolHarness(deployMinimal(address(instance), "")); } } pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../comptroller/Comptroller.sol"; /* solium-disable security/no-block-members */ contract ComptrollerHarness is Comptroller { uint256 internal time; function setCurrentTime(uint256 _time) external { time = _time; } function _currentTime() internal override view returns (uint256) { return time; } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "./ERC20Mintable.sol"; contract CTokenMock is ERC20Upgradeable { mapping(address => uint256) internal ownerTokenAmounts; ERC20Mintable public underlying; uint256 internal __supplyRatePerBlock; constructor ( ERC20Mintable _token, uint256 _supplyRatePerBlock ) public { require(address(_token) != address(0), "token is not defined"); underlying = _token; __supplyRatePerBlock = _supplyRatePerBlock; } function mint(uint256 amount) external returns (uint) { uint256 newCTokens; if (totalSupply() == 0) { newCTokens = amount; } else { // they need to hold the same assets as tokens. // Need to calculate the current exchange rate uint256 fractionOfCredit = FixedPoint.calculateMantissa(amount, underlying.balanceOf(address(this))); newCTokens = FixedPoint.multiplyUintByMantissa(totalSupply(), fractionOfCredit); } _mint(msg.sender, newCTokens); require(underlying.transferFrom(msg.sender, address(this), amount), "could not transfer tokens"); return 0; } function getCash() external view returns (uint) { return underlying.balanceOf(address(this)); } function redeemUnderlying(uint256 requestedAmount) external returns (uint) { uint256 cTokens = cTokenValueOf(requestedAmount); _burn(msg.sender, cTokens); require(underlying.transfer(msg.sender, requestedAmount), "could not transfer tokens"); } function accrue() external { uint256 newTokens = (underlying.balanceOf(address(this)) * 120) / 100; underlying.mint(address(this), newTokens); } function accrueCustom(uint256 amount) external { underlying.mint(address(this), amount); } function burn(uint256 amount) external { underlying.burn(address(this), amount); } function cTokenValueOf(uint256 tokens) public view returns (uint256) { return FixedPoint.divideUintByMantissa(tokens, exchangeRateCurrent()); } function balanceOfUnderlying(address account) public view returns (uint) { return FixedPoint.multiplyUintByMantissa(balanceOf(account), exchangeRateCurrent()); } function exchangeRateCurrent() public view returns (uint256) { if (totalSupply() == 0) { return FixedPoint.SCALE; } else { return FixedPoint.calculateMantissa(underlying.balanceOf(address(this)), totalSupply()); } } function supplyRatePerBlock() external view returns (uint) { return __supplyRatePerBlock; } function setSupplyRateMantissa(uint256 _supplyRatePerBlock) external { __supplyRatePerBlock = _supplyRatePerBlock; } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20Upgradeable { constructor(string memory _name, string memory _symbol) public { __ERC20_init(_name, _symbol); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public returns (bool) { _mint(account, amount); return true; } function burn(address account, uint256 amount) public returns (bool) { _burn(account, amount); return true; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../external/maker/DaiInterface.sol"; contract Dai is DaiInterface { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (uint256 chainId_) public { string memory version = "1"; _name = "Dai Stablecoin"; _symbol = "DAI"; _decimals = 18; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(_name)), keccak256(bytes(version)), chainId_, address(this) ) ); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "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 { _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 { } mapping (address => uint) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; // --- Approve by signature --- function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external override { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed ) ) ) ); require(holder != address(0), "Dai/invalid-address-0"); require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit"); require(expiry == 0 || now <= expiry, "Dai/permit-expired"); require(nonce == nonces[holder]++, "Dai/invalid-nonce"); uint wad = allowed ? uint(-1) : 0; _allowances[holder][spender] = wad; emit Approval(holder, spender, wad); } function mint(address to, uint256 amount) external { _mint(to, amount); } } pragma solidity >=0.6.0 <0.7.0; /* solium-disable security/no-inline-assembly */ contract DoppelgangerWithExec { struct MockCall { bool initialized; bool reverts; bytes returnValue; } mapping(bytes32 => MockCall) mockConfig; fallback() external payable { MockCall storage mockCall = __internal__getMockCall(); if (mockCall.reverts == true) { __internal__mockRevert(); return; } __internal__mockReturn(mockCall.returnValue); } function __waffle__mockReverts(bytes memory data) public { mockConfig[keccak256(data)] = MockCall({ initialized: true, reverts: true, returnValue: "" }); } function __waffle__mockReturns(bytes memory data, bytes memory value) public { mockConfig[keccak256(data)] = MockCall({ initialized: true, reverts: false, returnValue: value }); } function __waffle__call(address target, bytes calldata data) external returns (bytes memory) { (bool succeeded, bytes memory returnValue) = target.call(data); require(succeeded, string(returnValue)); return returnValue; } function __waffle__staticcall(address target, bytes calldata data) external view returns (bytes memory) { (bool succeeded, bytes memory returnValue) = target.staticcall(data); require(succeeded, string(returnValue)); return returnValue; } function __internal__getMockCall() view private returns (MockCall storage mockCall) { mockCall = mockConfig[keccak256(msg.data)]; if (mockCall.initialized == true) { // Mock method with specified arguments return mockCall; } mockCall = mockConfig[keccak256(abi.encodePacked(msg.sig))]; if (mockCall.initialized == true) { // Mock method with any arguments return mockCall; } revert("Mock on the method is not initialized"); } function __internal__mockReturn(bytes memory ret) pure private { assembly { return (add(ret, 0x20), mload(ret)) } } function __internal__mockRevert() pure private { revert("Mock revert"); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC1820ImplementerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC777/IERC777RecipientUpgradeable.sol"; import "../Constants.sol"; contract ERC1820ImplementerMock is IERC1820ImplementerUpgradeable, IERC777RecipientUpgradeable { constructor () public { Constants.REGISTRY.setInterfaceImplementer(address(this), Constants.TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function canImplementInterfaceForAddress(bytes32, address) external view virtual override returns(bytes32) { return Constants.ACCEPT_MAGIC; } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface for an ERC1820 implementer, as defined in the * https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP]. * Used by contracts that will be registered as implementers in the * {IERC1820Registry}. */ interface IERC1820ImplementerUpgradeable { /** * @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract * implements `interfaceHash` for `account`. * * See {IERC1820Registry-setInterfaceImplementer}. */ function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777RecipientUpgradeable { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; /** * @dev Extension of {ERC721} for Minting/Burning */ contract ERC721Mintable is ERC721Upgradeable { constructor () public { __ERC721_init("ERC 721", "NFT"); } /** * @dev See {ERC721-_mint}. */ function mint(address to, uint256 tokenId) public { _mint(to, tokenId); } /** * @dev See {ERC721-_burn}. */ function burn(uint256 tokenId) public { _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // 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 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 override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).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(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, 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 returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 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 = 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 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 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 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 returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev 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 = ownerOf(tokenId); _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(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); _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( IERC721ReceiverUpgradeable(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(ownerOf(tokenId), to, tokenId); } /** * @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 { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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 pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface 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 pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } pragma solidity >=0.6.0 <0.7.0; import "../utils/ExtendedSafeCast.sol"; contract ExtendedSafeCastExposed { function toUint112(uint256 value) external pure returns (uint112) { return ExtendedSafeCast.toUint112(value); } function toUint96(uint256 value) external pure returns (uint96) { return ExtendedSafeCast.toUint96(value); } } pragma solidity >=0.6.0 <0.7.0; import "../utils/MappedSinglyLinkedList.sol"; contract MappedSinglyLinkedListExposed { using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; MappedSinglyLinkedList.Mapping list; function initialize() external { list.initialize(); } function addressArray() external view returns (address[] memory) { return list.addressArray(); } function addAddresses(address[] calldata addresses) external { list.addAddresses(addresses); } function addAddress(address newAddress) external { list.addAddress(newAddress); } function removeAddress(address prevAddress, address addr) external { list.removeAddress(prevAddress, addr); } function contains(address addr) external view returns (bool) { return list.contains(addr); } function clearAll() external { list.clearAll(); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../prize-strategy/multiple-winners/MultipleWinners.sol"; /// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy. contract MultipleWinnersHarness is MultipleWinners { uint256 public currentTime; function setCurrentTime(uint256 _currentTime) external { currentTime = _currentTime; } function _currentTime() internal override view returns (uint256) { return currentTime; } function distribute(uint256 randomNumber) external { _distribute(randomNumber); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./MultipleWinnersHarness.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy. contract MultipleWinnersHarnessProxyFactory is ProxyFactory { MultipleWinnersHarness public instance; constructor () public { instance = new MultipleWinnersHarness(); } function create() external returns (MultipleWinnersHarness) { return MultipleWinnersHarness(deployMinimal(address(instance), "")); } } pragma solidity >=0.6.0 <0.7.0; import "../prize-strategy/PeriodicPrizeStrategy.sol"; /* solium-disable security/no-block-members */ interface PeriodicPrizeStrategyDistributorInterface { function distribute(uint256 randomNumber) external; } pragma solidity >=0.6.0 <0.7.0; import "../prize-strategy/PeriodicPrizeStrategy.sol"; import "./PeriodicPrizeStrategyDistributorInterface.sol"; import "@nomiclabs/buidler/console.sol"; /* solium-disable security/no-block-members */ contract PeriodicPrizeStrategyHarness is PeriodicPrizeStrategy { PeriodicPrizeStrategyDistributorInterface distributor; function setDistributor(PeriodicPrizeStrategyDistributorInterface _distributor) external { distributor = _distributor; } uint256 internal time; function setCurrentTime(uint256 _time) external { time = _time; } function _currentTime() internal override view returns (uint256) { return time; } function setRngRequest(uint32 requestId, uint32 lockBlock) external { rngRequest.id = requestId; rngRequest.lockBlock = lockBlock; } function _distribute(uint256 randomNumber) internal override { console.log("random number: ", randomNumber); distributor.distribute(randomNumber); } } pragma solidity >=0.6.0 <0.7.0; import "../prize-pool/PrizePool.sol"; import "./YieldSourceStub.sol"; contract PrizePoolHarness is PrizePool { uint256 public currentTime; YieldSourceStub stubYieldSource; function initializeAll( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration, YieldSourceStub _stubYieldSource ) public { PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa, _maxTimelockDuration ); stubYieldSource = _stubYieldSource; } function supply(uint256 mintAmount) external { _supply(mintAmount); } function redeem(uint256 redeemAmount) external { _redeem(redeemAmount); } function setCurrentTime(uint256 _currentTime) external { currentTime = _currentTime; } function setTimelockBalance(uint256 _timelockBalance) external { timelockTotalSupply = _timelockBalance; } function _currentTime() internal override view returns (uint256) { return currentTime; } function _canAwardExternal(address _externalToken) internal override view returns (bool) { return stubYieldSource.canAwardExternal(_externalToken); } function _token() internal override view returns (IERC20Upgradeable) { return stubYieldSource.token(); } function _balance() internal override returns (uint256) { return stubYieldSource.balance(); } function _supply(uint256 mintAmount) internal override { return stubYieldSource.supply(mintAmount); } function _redeem(uint256 redeemAmount) internal override returns (uint256) { return stubYieldSource.redeem(redeemAmount); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface YieldSourceStub { function canAwardExternal(address _externalToken) external view returns (bool); function token() external view returns (IERC20Upgradeable); function balance() external returns (uint256); function supply(uint256 mintAmount) external; function redeem(uint256 redeemAmount) external returns (uint256); } pragma solidity >=0.6.0 <0.7.0; import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol"; contract RNGServiceMock is RNGInterface { uint256 internal random; address internal feeToken; uint256 internal requestFee; function getLastRequestId() external override view returns (uint32 requestId) { return 1; } function setRequestFee(address _feeToken, uint256 _requestFee) external { feeToken = _feeToken; requestFee = _requestFee; } /// @return _feeToken /// @return _requestFee function getRequestFee() external override view returns (address _feeToken, uint256 _requestFee) { return (feeToken, requestFee); } function setRandomNumber(uint256 _random) external { random = _random; } function requestRandomNumber() external override returns (uint32, uint32) { return (1, 1); } function isRequestComplete(uint32) external override view returns (bool) { return true; } function randomNumber(uint32) external override returns (uint256) { return random; } } pragma solidity >=0.6.0 <0.7.0; import "../prize-strategy/single-random-winner/SingleRandomWinner.sol"; /* solium-disable security/no-block-members */ contract SingleRandomWinnerHarness is SingleRandomWinner { uint256 internal time; function setCurrentTime(uint256 _time) external { time = _time; } function _currentTime() internal override view returns (uint256) { return time; } function setRngRequest(uint32 requestId, uint32 lockBlock) external { rngRequest.id = requestId; rngRequest.lockBlock = lockBlock; } function distribute(uint256 randomNumber) external { _distribute(randomNumber); } } pragma solidity >=0.6.0 <0.7.0; /* solium-disable security/no-block-members */ contract Timestamp { function blockTime() public view returns (uint256) { return block.timestamp; } } pragma solidity >=0.6.0 <0.7.0; import "../utils/UInt256Array.sol"; contract UInt256ArrayExposed { using UInt256Array for uint256[]; uint256[] internal array; constructor (uint256[] memory _array) public { array = new uint256[](_array.length); for (uint256 i = 0; i < _array.length; i++) { array[i] = _array[i]; } } function remove(uint256 index) external { array.remove(index); } function toArray() external view returns (uint256[] memory) { return array; } } pragma solidity >=0.6.0 <0.7.0; import "../drip/VolumeDrip.sol"; contract VolumeDripExposed { using VolumeDrip for VolumeDrip.State; event DripTokensBurned(address user, uint256 amount); event Minted(uint256 amount); event MintedTotalSupply(uint256 amount); VolumeDrip.State state; function setNewPeriod(uint32 periodSeconds, uint112 dripAmount, uint32 endTime) external { state.setNewPeriod(periodSeconds, dripAmount, endTime); } function setNextPeriod(uint32 periodSeconds, uint112 dripAmount) external { state.setNextPeriod(periodSeconds, dripAmount); } function drip(uint256 currentTime, uint256 maxNewTokens) external returns (uint256) { uint256 newTokens = state.drip(currentTime, maxNewTokens); emit MintedTotalSupply(newTokens); return newTokens; } function mint(address user, uint256 amount) external returns (uint256) { uint256 accrued = state.mint(user, amount); emit Minted(accrued); return accrued; } function getDrip() external view returns ( uint32 periodSeconds, uint128 dripAmount ) { periodSeconds = state.nextPeriodSeconds; dripAmount = state.nextDripAmount; } function getPeriod(uint32 period) external view returns ( uint112 totalSupply, uint112 dripAmount, uint32 endTime ) { totalSupply = state.periods[period].totalSupply; endTime = state.periods[period].endTime; dripAmount = state.periods[period].dripAmount; } function getDeposit(address user) external view returns ( uint112 balance, uint32 period ) { balance = state.deposits[user].balance; period = state.deposits[user].period; } } pragma solidity >=0.6.0 <0.7.0; import "../drip/VolumeDripManager.sol"; contract VolumeDripManagerExposed { using VolumeDripManager for VolumeDripManager.State; using VolumeDrip for VolumeDrip.State; VolumeDripManager.State manager; function activate( address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount, uint32 endTime ) external { manager.activate(measure, dripToken, periodSeconds, dripAmount, endTime); } function deactivate( address measure, address dripToken, address prevDripToken ) external { manager.deactivate(measure, dripToken, prevDripToken); } function set(address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount) external { manager.set(measure, dripToken, periodSeconds, dripAmount); } function isActive(address measure, address dripToken) external view returns (bool) { return manager.isActive(measure, dripToken); } function getPeriod( address measure, address dripToken, uint32 period ) external view returns ( uint112 totalSupply, uint112 dripAmount, uint32 endTime ) { VolumeDrip.State storage drip = manager.getDrip(measure, dripToken); VolumeDrip.Period memory state = drip.periods[period]; totalSupply = state.totalSupply; dripAmount = state.dripAmount; endTime = state.endTime; } function getActiveVolumeDrips(address measure) external view returns (address[] memory) { return manager.getActiveVolumeDrips(measure); } function getDrip( address measure, address dripToken ) external view returns ( uint32 periodSeconds, uint112 dripAmount ) { VolumeDrip.State storage drip = manager.getDrip(measure, dripToken); dripAmount = drip.nextDripAmount; periodSeconds = drip.nextPeriodSeconds; } } pragma solidity >=0.6.0 <0.7.0; import "../external/yearn/yVaultInterface.sol"; import "./ERC20Mintable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; contract yVaultMock is yVaultInterface, ERC20Upgradeable { ERC20Upgradeable private asset; uint256 public vaultFeeMantissa; constructor (ERC20Mintable _asset) public { asset = _asset; vaultFeeMantissa = 0.05 ether; } function token() external override view returns (IERC20Upgradeable) { return asset; } function balance() public override view returns (uint) { return asset.balanceOf(address(this)); } function removeLiquidity(uint _amount) external { asset.transfer(msg.sender, _amount); } function setVaultFeeMantissa(uint256 _vaultFeeMantissa) external { vaultFeeMantissa = _vaultFeeMantissa; } function deposit(uint _amount) external override { uint _pool = balance(); uint _before = asset.balanceOf(address(this)); asset.transferFrom(msg.sender, address(this), _amount); uint _after = asset.balanceOf(address(this)); uint diff = _after.sub(_before); // Additional check for deflationary assets uint shares = 0; if (totalSupply() == 0) { shares = diff; } else { shares = (diff.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdraw(uint _shares) external override { uint256 sharesFee = FixedPoint.multiplyUintByMantissa(_shares, vaultFeeMantissa); uint256 withdrawal = (balance().mul(_shares.sub(sharesFee))).div(totalSupply()); asset.transfer(msg.sender, withdrawal); _mint(address(this), sharesFee); _burn(msg.sender, _shares); } function getPricePerFullShare() external override view returns (uint) { return balance().mul(1e18).div(totalSupply()); } } pragma solidity >=0.6.0 <0.7.0; import "../prize-pool/yearn/yVaultPrizePool.sol"; contract yVaultPrizePoolHarness is yVaultPrizePool { uint256 public currentTime; function setCurrentTime(uint256 _currentTime) external { currentTime = _currentTime; } function _currentTime() internal override view returns (uint256) { return currentTime; } function supply(uint256 mintAmount) external { _supply(mintAmount); } function redeem(uint256 redeemAmount) external returns (uint256) { return _redeem(redeemAmount); } } pragma solidity >=0.6.0 <0.7.0; import "./yVaultPrizePoolHarness.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Compound Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new Compound Prize Pools contract yVaultPrizePoolHarnessProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools yVaultPrizePoolHarness public instance; /// @notice Initializes the Factory with an instance of the Compound Prize Pool constructor () public { instance = new yVaultPrizePoolHarness(); } /// @notice Creates a new Compound Prize Pool as a proxy of the template instance /// @return A reference to the new proxied Compound Prize Pool function create() external returns (yVaultPrizePoolHarness) { return yVaultPrizePoolHarness(deployMinimal(address(instance), "")); } }
Activates a balance drip. Only callable by the owner. source The balance drip "source"; i.e. a Prize Pool address. measure The ERC20 token whose balances determines user's share of the drip rate. dripToken The token that is dripped to users. dripRatePerSecond The amount of drip tokens that are awarded each second to the total supply of measure.
function activateBalanceDrip(address source, address measure, address dripToken, uint256 dripRatePerSecond) external onlyOwner { balanceDrips[source].activateDrip(measure, dripToken, dripRatePerSecond); emit BalanceDripActivated( source, measure, dripToken, dripRatePerSecond ); }
12,863,598
pragma solidity ^0.4.19; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; uint256 totalRecycledTokens_; bool public paused = false; bool public tgeMode = false; address public ceoAddress; address public marketplaceAddress; function totalSupply() public view returns (uint256) { return totalSupply_; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } modifier onlyCEO() { require(msg.sender == ceoAddress); _; } function pause() public onlyCEO() whenNotPaused() { paused = true; } function unpause() public onlyCEO() whenPaused() { paused = false; } modifier inTGE() { require(tgeMode); _; } modifier afterTGE() { require(!tgeMode); _; } /** * @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 whenNotPaused() returns (bool) { require( !tgeMode || (msg.sender == ceoAddress) ); require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ExoToken is ERC20, BasicToken { string public name = "ExoToken"; string public symbol = "EXT"; uint8 public decimals = 18; uint256 public MaxNumTokens = 175000000000000000000000000; uint256 private priceOfToken; mapping (address => mapping (address => uint256)) internal allowed; mapping(address => bool) private tgeUserMap; address[] private tgeUserList; event Mint(address _to, uint256 _amount); event RecycleTokens(uint256 value); uint32 public bonusFactor_1 = 5; uint32 public bonusFactor_2 = 10; uint32 public bonusFactor_3 = 20; function setBonusFactors(uint32 factor_1, uint32 factor_2, uint32 factor_3) public onlyCEO() inTGE() { bonusFactor_1 = factor_1; bonusFactor_2 = factor_2; bonusFactor_3 = factor_3; } /*** CONSTRUCTOR ***/ function ExoToken(uint256 initialSupply, uint256 initialPriceOfToken) public { // set initialSupply to e.g. 82,250,000 require(initialPriceOfToken > 0); ceoAddress = msg.sender; marketplaceAddress = msg.sender; priceOfToken = initialPriceOfToken; balances[msg.sender] = initialSupply; totalSupply_ = initialSupply; } /** * @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 whenNotPaused() afterTGE() 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 whenNotPaused() afterTGE() 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) whenNotPaused() public view returns (uint256) { return allowed[_owner][_spender]; } function setPriceOfToken(uint256 newPriceOfToken) public onlyCEO() { require(newPriceOfToken > 0); priceOfToken = newPriceOfToken; } function getPriceOfToken() public view returns(uint256) { return priceOfToken; } function getNumRecycledTokens() public view returns(uint256) { return totalRecycledTokens_; } function recycleTokensForPayment(uint256 numTokens, uint256 payment) public onlyCEO() { require(payment <= this.balance); recycleTokens(numTokens); ceoAddress.transfer(payment); } function recycleTokens(uint256 numTokens) public onlyCEO() { // allow more tokens to be minted require(numTokens <= balances[ceoAddress]); totalSupply_ = totalSupply_.sub(numTokens); balances[ceoAddress] = balances[ceoAddress].sub(numTokens); totalRecycledTokens_ = totalRecycledTokens_.add(numTokens); RecycleTokens(numTokens); } uint256 public firstBonusStep = 1 ether; uint256 public secondBonusStep = 5 ether; uint256 public thirdBonusStep = 10 ether; function setBonusSteps(uint256 step_1, uint256 step_2, uint256 step_3) public onlyCEO() inTGE() { firstBonusStep = step_1; secondBonusStep = step_2; thirdBonusStep = step_3; } function purchase() public payable whenNotPaused() inTGE() { /// when in TGE - buy tokens (from CEO account) for ETH uint256 amount = msg.value.div(priceOfToken); require(amount > 0); if (tgeUserMap[ msg.sender] == false) { // In Solidity, mapping will return the default value for each key type tgeUserMap[ msg.sender] = true; tgeUserList.push( msg.sender); } uint bonusFactor; if (msg.value < firstBonusStep) { bonusFactor = 100; // no bonus } else if (msg.value < secondBonusStep) { bonusFactor = 100 + bonusFactor_1; } else if (msg.value < thirdBonusStep) { bonusFactor = 100 + bonusFactor_2; } else { bonusFactor = 100 + bonusFactor_3; } amount = amount.mul(bonusFactor).div(100); amount = amount.mul(1000000000000000000); /// mint requested amount of tokens doMint(msg.sender, amount); /// Transfer tokens from ceo to msg.sender // require(amount <= balances[ceoAddress]); // balances[ceoAddress] = balances[ceoAddress].sub(amount); // balances[msg.sender] = balances[msg.sender].add(amount); // Transfer(ceoAddress, msg.sender, amount); } /// mint function - either by CEO or from site function mintTokens(address buyerAddress, uint256 amount) public whenNotPaused() returns (bool) { require(msg.sender == marketplaceAddress || msg.sender == ceoAddress); return doMint(buyerAddress, amount); } function doMint(address buyerAddress, uint256 amount) private whenNotPaused() returns (bool) { require( totalSupply_.add(amount) <= MaxNumTokens); totalSupply_ = totalSupply_.add(amount); balances[buyerAddress] = balances[buyerAddress].add(amount); Mint(buyerAddress, amount); return true; } function getNumTGEUsers() public view returns (uint256) { return tgeUserList.length; } function getTGEUser( uint32 ind) public view returns (address) { return tgeUserList[ind]; } function payout() public onlyCEO { ceoAddress.transfer(this.balance); } function payoutPartial(uint256 amount) public onlyCEO { require(amount <= this.balance); ceoAddress.transfer(amount); } function setTGEMode(bool newMode) public onlyCEO { tgeMode = newMode; } function setCEO(address newCEO) public onlyCEO { require(newCEO != address(0)); uint256 ceoTokens = balances[ceoAddress]; balances[ceoAddress] = 0; balances[newCEO] = balances[newCEO].add(ceoTokens); ceoAddress = newCEO; } function setMarketplaceAddress(address newMarketplace) public onlyCEO { marketplaceAddress = newMarketplace; } /** * @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) whenNotPaused() 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) whenNotPaused() 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; } } 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; } }
allow more tokens to be minted
function recycleTokens(uint256 numTokens) public onlyCEO() { require(numTokens <= balances[ceoAddress]); totalSupply_ = totalSupply_.sub(numTokens); balances[ceoAddress] = balances[ceoAddress].sub(numTokens); totalRecycledTokens_ = totalRecycledTokens_.add(numTokens); RecycleTokens(numTokens); } uint256 public firstBonusStep = 1 ether; uint256 public secondBonusStep = 5 ether; uint256 public thirdBonusStep = 10 ether;
7,231,597
pragma solidity ^0.4.23; /* * The Blockchain Football network presents.... * https://fantasyfootballfund.co/ * https://discord.gg/qPjA6Tx * * Build your fantasy player portfolio. Earn crypto daily based on player performance. * * 4 Ways to earn * [1] Price Fluctuations - buy and sell at the right moments * [2] Match day Divs - allocated to shareholders of top performing players every day * [3] Fame Divs - allocated to shareholders of infamous players on non-match days * [4] Original Owner - allocated to owners of original player cards on blockchainfootball.co (2% per share sold) */ contract ERC20 { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view 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 PlayerToken is ERC20 { // Ownable address public owner; bool public paused = false; // Events event PlayerTokenBuy(address indexed buyer, address indexed referrer, uint tokens, uint cost, string symbol); event PlayerTokenSell(address indexed seller, uint tokens, uint value, string symbol); // Libs using SafeMath for uint256; // Core token attributes uint256 public initialTokenPrice_; // Typically = 1 Finney (0.001 Ether) uint256 public incrementalTokenPrice_; // Typically = 0.01 Finney (0.00001 Ether) // Token Properties - set via the constructor for each player string public name; string public symbol; uint8 public constant decimals = 0; // Exchange Contract - used to hold the dividend pool across all ERC20 player contracts // when shares are brought or sold the dividend fee gets transfered here address public exchangeContract_; // Blockchainfootball.co attributes - if this is set the owner receieves a fee for owning the original card BCFMain bcfContract_ = BCFMain(0x6abF810730a342ADD1374e11F3e97500EE774D1F); uint256 public playerId_; address public originalOwner_; // Fees - denoted in % uint8 constant internal processingFee_ = 5; // inc. fees to cover DAILY gas usage to assign divs to token holders uint8 constant internal originalOwnerFee_ = 2; // of all token buys per original player owned + set on blockchainfootball.co uint8 internal dividendBuyPoolFee_ = 15; // buys AND sells go into the div pool to promote gameplay - can be updated uint8 internal dividendSellPoolFee_ = 20; uint8 constant internal referrerFee_ = 1; // for all token buys (but not sells) // ERC20 data structures mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) internal allowed; // Player Exchange Data Structures address[] public tokenHolders; mapping(address => uint256) public addressToTokenHolderIndex; // Helps to gas-efficiently remove shareholders, by swapping last index mapping(address => int256) public totalCost; // To hold the total expenditure of each address, profit tracking // ERC20 Properties uint256 totalSupply_; // Additional accessors modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyOwnerOrExchange() { require(msg.sender == owner || msg.sender == exchangeContract_); _; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } // Constructor constructor( string _name, string _symbol, uint _startPrice, uint _incrementalPrice, address _owner, address _exchangeContract, uint256 _playerId, uint8 _promoSharesQuantity ) public payable { require(_exchangeContract != address(0)); require(_owner != address(0)); exchangeContract_ = _exchangeContract; playerId_ = _playerId; // Set initial starting exchange values initialTokenPrice_ = _startPrice; incrementalTokenPrice_ = _incrementalPrice; // In most cases this will be 1 finney, 0.001 ETH // Initial token properties paused = true; owner = _owner; name = _name; symbol = _symbol; // Purchase promotional player shares - we purchase initial shares (the same way users do) as prizes for promos/competitions/giveaways if (_promoSharesQuantity > 0) { _buyTokens(msg.value, _promoSharesQuantity, _owner, address(0)); } } // **External Exchange** function buyTokens(uint8 _amount, address _referredBy) payable external whenNotPaused { require(_amount > 0 && _amount <= 100, "Valid token amount required between 1 and 100"); require(msg.value > 0, "Provide a valid fee"); // solium-disable-next-line security/no-tx-origin require(msg.sender == tx.origin, "Only valid users are allowed to buy tokens"); _buyTokens(msg.value, _amount, msg.sender, _referredBy); } function sellTokens(uint8 _amount) external { require(_amount > 0, "Valid sell amount required"); require(_amount <= balances[msg.sender]); _sellTokens(_amount, msg.sender); } // **Internal Exchange** function _buyTokens(uint _ethSent, uint8 _amount, address _buyer, address _referredBy) internal { uint _totalCost; uint _processingFee; uint _originalOwnerFee; uint _dividendPoolFee; uint _referrerFee; (_totalCost, _processingFee, _originalOwnerFee, _dividendPoolFee, _referrerFee) = calculateTokenBuyPrice(_amount); require(_ethSent >= _totalCost, "Invalid fee to buy tokens"); // Send to original card owner if available // If we don&#39;t have an original owner we move this fee into the dividend pool if (originalOwner_ != address(0)) { originalOwner_.transfer(_originalOwnerFee); } else { _dividendPoolFee = _dividendPoolFee.add(_originalOwnerFee); } // Send to the referrer - if we don&#39;t have a referrer we move this fee into the dividend pool if (_referredBy != address(0)) { _referredBy.transfer(_referrerFee); } else { _dividendPoolFee = _dividendPoolFee.add(_referrerFee); } // These will always be available owner.transfer(_processingFee); exchangeContract_.transfer(_dividendPoolFee); // Refund excess uint excess = _ethSent.sub(_totalCost); _buyer.transfer(excess); // Track ownership of token holders - only if this is the first time the user is buying these player shares if (balanceOf(_buyer) == 0) { tokenHolders.push(_buyer); addressToTokenHolderIndex[_buyer] = tokenHolders.length - 1; } // Provide users with the shares _allocatePlayerTokensTo(_buyer, _amount); // Track costs totalCost[_buyer] = totalCost[_buyer] + int256(_totalCost); // No need for safe maths here, just holds profit tracking // Event tracking emit PlayerTokenBuy(_buyer, _referredBy, _amount, _totalCost, symbol); } function _sellTokens(uint8 _amount, address _seller) internal { uint _totalSellerProceeds; uint _processingFee; uint _dividendPoolFee; (_totalSellerProceeds, _processingFee, _dividendPoolFee) = calculateTokenSellPrice(_amount); // Burn the sellers shares _burnPlayerTokensFrom(_seller, _amount); // Track ownership of token holders if the user no longer has tokens let&#39;s remove them // we do this semi-efficently by swapping the last index if (balanceOf(_seller) == 0) { removeFromTokenHolders(_seller); } // Transfer to processor, seller and dividend pool owner.transfer(_processingFee); _seller.transfer(_totalSellerProceeds); exchangeContract_.transfer(_dividendPoolFee); // Track costs totalCost[_seller] = totalCost[_seller] - int256(_totalSellerProceeds); // No need for safe maths here, just holds profit tracking // Event tracking emit PlayerTokenSell(_seller, _amount, _totalSellerProceeds, symbol); } // **Calculations - these factor in all fees** function calculateTokenBuyPrice(uint _amount) public view returns ( uint _totalCost, uint _processingFee, uint _originalOwnerFee, uint _dividendPoolFee, uint _referrerFee ) { uint tokenCost = calculateTokenOnlyBuyPrice(_amount); // We now need to apply fees on top of this // In all cases we apply fees - but if there&#39;s no original owner or referrer // these go into the dividend pool _processingFee = SafeMath.div(SafeMath.mul(tokenCost, processingFee_), 100); _originalOwnerFee = SafeMath.div(SafeMath.mul(tokenCost, originalOwnerFee_), 100); _dividendPoolFee = SafeMath.div(SafeMath.mul(tokenCost, dividendBuyPoolFee_), 100); _referrerFee = SafeMath.div(SafeMath.mul(tokenCost, referrerFee_), 100); _totalCost = tokenCost.add(_processingFee).add(_originalOwnerFee).add(_dividendPoolFee).add(_referrerFee); } function calculateTokenSellPrice(uint _amount) public view returns ( uint _totalSellerProceeds, uint _processingFee, uint _dividendPoolFee ) { uint tokenSellCost = calculateTokenOnlySellPrice(_amount); // We remove the processing and dividend fees on the final sell price // this represents the difference between the buy and sell price on the UI _processingFee = SafeMath.div(SafeMath.mul(tokenSellCost, processingFee_), 100); _dividendPoolFee = SafeMath.div(SafeMath.mul(tokenSellCost, dividendSellPoolFee_), 100); _totalSellerProceeds = tokenSellCost.sub(_processingFee).sub(_dividendPoolFee); } // **Calculate total cost of tokens without fees** function calculateTokenOnlyBuyPrice(uint _amount) public view returns(uint) { // We use a simple arithmetic progression series, summing the incremental prices // ((n / 2) * (2 * a + (n - 1) * d)) // a = starting value (1st term), d = price increment (diff.), n = amount of shares (no. of terms) // NOTE: we use a mutiplier to avoid issues with an odd number of shares, dividing and limited fixed point support in Solidity uint8 multiplier = 10; uint amountMultiplied = _amount * multiplier; uint startingPrice = initialTokenPrice_ + (totalSupply_ * incrementalTokenPrice_); uint totalBuyPrice = (amountMultiplied / 2) * (2 * startingPrice + (_amount - 1) * incrementalTokenPrice_) / multiplier; // Should never *concievably* occur, but more effecient than Safemaths on the entire formula assert(totalBuyPrice >= startingPrice); return totalBuyPrice; } function calculateTokenOnlySellPrice(uint _amount) public view returns(uint) { // Similar to calculateTokenBuyPrice, but we abs() the incrementalTokenPrice so we get a reverse arithmetic series uint8 multiplier = 10; uint amountMultiplied = _amount * multiplier; uint startingPrice = initialTokenPrice_ + ((totalSupply_-1) * incrementalTokenPrice_); int absIncrementalTokenPrice = int(incrementalTokenPrice_) * -1; uint totalSellPrice = uint((int(amountMultiplied) / 2) * (2 * int(startingPrice) + (int(_amount) - 1) * absIncrementalTokenPrice) / multiplier); return totalSellPrice; } // **UI Helpers** function buySellPrices() public view returns(uint _buyPrice, uint _sellPrice) { (_buyPrice,,,,) = calculateTokenBuyPrice(1); (_sellPrice,,) = calculateTokenSellPrice(1); } function portfolioSummary(address _address) public view returns(uint _tokenBalance, int _cost, uint _value) { _tokenBalance = balanceOf(_address); _cost = totalCost[_address]; (_value,,) = calculateTokenSellPrice(_tokenBalance); } function totalTokenHolders() public view returns(uint) { return tokenHolders.length; } function tokenHoldersByIndex() public view returns(address[] _addresses, uint[] _shares) { // This will only be called offchain to take snapshots of share count at cut off points for divs uint tokenHolderCount = tokenHolders.length; address[] memory addresses = new address[](tokenHolderCount); uint[] memory shares = new uint[](tokenHolderCount); for (uint i = 0; i < tokenHolderCount; i++) { addresses[i] = tokenHolders[i]; shares[i] = balanceOf(tokenHolders[i]); } return (addresses, shares); } // In cases where there&#39;s bugs in the exchange contract we need a way to re-point function setExchangeContractAddress(address _exchangeContract) external onlyOwner { exchangeContract_ = _exchangeContract; } // **Blockchainfootball.co Support** function setBCFContractAddress(address _address) external onlyOwner { BCFMain candidateContract = BCFMain(_address); require(candidateContract.implementsERC721()); bcfContract_ = candidateContract; } function setPlayerId(uint256 _playerId) external onlyOwner { playerId_ = _playerId; } function setSellDividendPercentageFee(uint8 _dividendPoolFee) external onlyOwnerOrExchange { // We&#39;ll need some flexibility to alter this as the right dividend structure helps promote gameplay // This pushes users to buy players who are performing well to grab divs rather than just getting in early to new players being released require(_dividendPoolFee <= 50, "Max of 50% is assignable to the pool"); dividendSellPoolFee_ = _dividendPoolFee; } function setBuyDividendPercentageFee(uint8 _dividendPoolFee) external onlyOwnerOrExchange { require(_dividendPoolFee <= 50, "Max of 50% is assignable to the pool"); dividendBuyPoolFee_ = _dividendPoolFee; } // Can be called by anyone, in which case we could use a another contract to set the original owner whenever it changes on blockchainfootball.co function setOriginalOwner(uint256 _playerCardId, address _address) external { require(playerId_ > 0, "Player ID must be set on the contract"); // As we call .transfer() on buys to send original owners divs we need to make sure this can&#39;t be DOS&#39;d through setting the // original owner as a smart contract and then reverting any transfer() calls // while it would be silly to reject divs it is a valid DOS scenario // solium-disable-next-line security/no-tx-origin require(msg.sender == tx.origin, "Only valid users are able to set original ownership"); address _cardOwner; uint256 _playerId; bool _isFirstGeneration; (_playerId,_cardOwner,,_isFirstGeneration) = bcfContract_.playerCards(_playerCardId); require(_isFirstGeneration, "Card must be an original"); require(_playerId == playerId_, "Card must tbe the same player this contract relates to"); require(_cardOwner == _address, "Card must be owned by the address provided"); // All good, set the address as the original owner, happy div day \o/ originalOwner_ = _address; } // ** Internal Token Handling - validation completed by callers ** function _allocatePlayerTokensTo(address _to, uint256 _amount) internal { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); } function _burnPlayerTokensFrom(address _from, uint256 _amount) internal { balances[_from] = balances[_from].sub(_amount); totalSupply_ = totalSupply_.sub(_amount); emit Transfer(_from, address(0), _amount); } function removeFromTokenHolders(address _seller) internal { uint256 tokenIndex = addressToTokenHolderIndex[_seller]; uint256 lastAddressIndex = tokenHolders.length.sub(1); address lastAddress = tokenHolders[lastAddressIndex]; tokenHolders[tokenIndex] = lastAddress; tokenHolders[lastAddressIndex] = address(0); tokenHolders.length--; addressToTokenHolderIndex[lastAddress] = tokenIndex; } // ** ERC20 Support ** function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value > 0); require(_value <= balances[msg.sender]); // Track ownership of token holders - only if this is the first time the user is buying these player shares if (balanceOf(_to) == 0) { tokenHolders.push(_to); addressToTokenHolderIndex[_to] = tokenHolders.length - 1; } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); // Track ownership of token holders if the user no longer has tokens let&#39;s remove them // we do this semi-efficently by swapping the last index if (balanceOf(msg.sender) == 0) { removeFromTokenHolders(msg.sender); } emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value > 0); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); // Track ownership of token holders - only if this is the first time the user is buying these player shares if (balanceOf(_to) == 0) { tokenHolders.push(_to); addressToTokenHolderIndex[_to] = tokenHolders.length - 1; } balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Track ownership of token holders if the user no longer has tokens let&#39;s remove them // we do this semi-efficently by swapping the last index if (balanceOf(_from) == 0) { removeFromTokenHolders(_from); } emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256){ return allowed[_owner][_spender]; } // Utilities function setOwner(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } function pause() onlyOwnerOrExchange whenNotPaused public { paused = true; } function unpause() onlyOwnerOrExchange whenPaused public { paused = false; } } contract BCFMain { function playerCards(uint256 playerCardId) public view returns (uint256 playerId, address owner, address approvedForTransfer, bool isFirstGeneration); function implementsERC721() public pure returns (bool); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } 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 c) { c = a + b; assert(c >= a); return c; } } contract PlayerExchangeCore { // Events event InitialPlayerOffering(address indexed contractAddress, string name, string symbol); event DividendWithdrawal(address indexed user, uint amount); // Libs using SafeMath for uint256; // Ownership address public owner; address public referee; // Used to pay out divs and initiate an IPO // Structs struct DividendWinner { uint playerTokenContractId; uint perTokenEthValue; uint totalTokens; uint tokensProcessed; // So we can determine when all tokens have been allocated divs + settled } // State management uint internal balancePendingWithdrawal_; // this.balance - balancePendingWithdrawal_ = div prize pool // Data Store PlayerToken[] public playerTokenContracts_; // Holds a list of all player token contracts DividendWinner[] public dividendWinners_; // Holds a list of dividend winners (player contract id&#39;s, not users) mapping(address => uint256) public addressToDividendBalance; // Modifiers modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyReferee() { require(msg.sender == referee); _; } modifier onlyOwnerOrReferee() { require(msg.sender == owner || msg.sender == referee); _; } function setOwner(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } function setReferee(address newReferee) public onlyOwner { require(newReferee != address(0)); referee = newReferee; } constructor(address _owner, address _referee) public { owner = _owner; referee = _referee; } // Create new instances of a PlayerToken contract and pass along msg.value (so the referee pays and not the contract) function newInitialPlayerOffering( string _name, string _symbol, uint _startPrice, uint _incrementalPrice, address _owner, uint256 _playerId, uint8 _promoSharesQuantity ) external onlyOwnerOrReferee payable { PlayerToken playerTokenContract = (new PlayerToken).value(msg.value)( _name, _symbol, _startPrice, _incrementalPrice, _owner, address(this), _playerId, _promoSharesQuantity ); // Add it to a local storage so we can iterate over it to pull portfolio stats playerTokenContracts_.push(playerTokenContract); // Event handling emit InitialPlayerOffering(address(playerTokenContract), _name, _symbol); } // Empty fallback - any Ether here just goes straight into the Dividend pool // this is useful as it provides a mechanism for the other blockchain football games // to top the fund up for special events / promotions function() payable public { } function getTotalDividendPool() public view returns (uint) { return address(this).balance.sub(balancePendingWithdrawal_); } function totalPlayerTokenContracts() public view returns (uint) { return playerTokenContracts_.length; } function totalDividendWinners() public view returns (uint) { return dividendWinners_.length; } // Called off-chain to manage UI state so no gas concerns - also never likely to be more than 50-200ish player contracts function allPlayerTokenContracts() external view returns (address[]) { uint playerContractCount = totalPlayerTokenContracts(); address[] memory addresses = new address[](playerContractCount); for (uint i = 0; i < playerContractCount; i++) { addresses[i] = address(playerTokenContracts_[i]); } return addresses; } /* Safeguard function to quickly pause a stack of contracts */ function pausePlayerContracts(uint startIndex, uint endIndex) onlyOwnerOrReferee external { for (uint i = startIndex; i < endIndex; i++) { PlayerToken playerTokenContract = playerTokenContracts_[i]; if (!playerTokenContract.paused()) { playerTokenContract.pause(); } } } function unpausePlayerContracts(uint startIndex, uint endIndex) onlyOwnerOrReferee external { for (uint i = startIndex; i < endIndex; i++) { PlayerToken playerTokenContract = playerTokenContracts_[i]; if (playerTokenContract.paused()) { playerTokenContract.unpause(); } } } function setSellDividendPercentageFee(uint8 _fee, uint startIndex, uint endIndex) onlyOwner external { for (uint i = startIndex; i < endIndex; i++) { PlayerToken playerTokenContract = playerTokenContracts_[i]; playerTokenContract.setSellDividendPercentageFee(_fee); } } function setBuyDividendPercentageFee(uint8 _fee, uint startIndex, uint endIndex) onlyOwner external { for (uint i = startIndex; i < endIndex; i++) { PlayerToken playerTokenContract = playerTokenContracts_[i]; playerTokenContract.setBuyDividendPercentageFee(_fee); } } /* Portfolio Support */ // Only called offchain - so we can omit additional pagination/optimizations here function portfolioSummary(address _address) external view returns ( uint[] _playerTokenContractId, uint[] _totalTokens, int[] _totalCost, uint[] _totalValue) { uint playerContractCount = totalPlayerTokenContracts(); uint[] memory playerTokenContractIds = new uint[](playerContractCount); uint[] memory totalTokens = new uint[](playerContractCount); int[] memory totalCost = new int[](playerContractCount); uint[] memory totalValue = new uint[](playerContractCount); PlayerToken playerTokenContract; for (uint i = 0; i < playerContractCount; i++) { playerTokenContract = playerTokenContracts_[i]; playerTokenContractIds[i] = i; (totalTokens[i], totalCost[i], totalValue[i]) = playerTokenContract.portfolioSummary(_address); } return (playerTokenContractIds, totalTokens, totalCost, totalValue); } /* Dividend Handling */ // These are all handled based on their corresponding index // Takes a snapshot of the current dividend pool balance and allocates a per share div award function setDividendWinners( uint[] _playerContractIds, uint[] _totalPlayerTokens, uint8[] _individualPlayerAllocationPcs, uint _totalPrizePoolAllocationPc ) external onlyOwnerOrReferee { require(_playerContractIds.length > 0, "Must have valid player contracts to award divs to"); require(_playerContractIds.length == _totalPlayerTokens.length); require(_totalPlayerTokens.length == _individualPlayerAllocationPcs.length); require(_totalPrizePoolAllocationPc > 0); require(_totalPrizePoolAllocationPc <= 100); // Calculate how much dividends we have allocated uint dailyDivPrizePool = SafeMath.div(SafeMath.mul(getTotalDividendPool(), _totalPrizePoolAllocationPc), 100); // Iteration here should be fine as there should concievably only ever be 3 or 4 winning players each day uint8 totalPlayerAllocationPc = 0; for (uint8 i = 0; i < _playerContractIds.length; i++) { totalPlayerAllocationPc += _individualPlayerAllocationPcs[i]; // Calculate from the total daily pool how much is assigned to owners of this player // e.g. a typical day might = Total Dividend pool: 100 ETH, _totalPrizePoolAllocationPc: 20 (%) // therefore the total dailyDivPrizePool = 20 ETH // Which could be allocated as follows // 1. 50% MVP Player - (Attacker) (10 ETH total) // 2. 25% Player - (Midfielder) (5 ETH total) // 3. 25% Player - (Defender) (5 ETH total) uint playerPrizePool = SafeMath.div(SafeMath.mul(dailyDivPrizePool, _individualPlayerAllocationPcs[i]), 100); // Calculate total div-per-share uint totalPlayerTokens = _totalPlayerTokens[i]; uint perTokenEthValue = playerPrizePool.div(totalPlayerTokens); // Add to the winners array so it can then be picked up by the div payment processor DividendWinner memory divWinner = DividendWinner({ playerTokenContractId: _playerContractIds[i], perTokenEthValue: perTokenEthValue, totalTokens: totalPlayerTokens, tokensProcessed: 0 }); dividendWinners_.push(divWinner); } // We need to make sure we are allocating a valid set of dividend totals (i.e. not more than 100%) // this is just to cover us for basic errors, this should never occur require(totalPlayerAllocationPc == 100); } function allocateDividendsToWinners(uint _dividendWinnerId, address[] _winners, uint[] _tokenAllocation) external onlyOwnerOrReferee { DividendWinner storage divWinner = dividendWinners_[_dividendWinnerId]; require(divWinner.totalTokens > 0); // Basic check to make sure we don&#39;t access a 0&#39;d struct require(divWinner.tokensProcessed < divWinner.totalTokens); require(_winners.length == _tokenAllocation.length); uint totalEthAssigned; uint totalTokensAllocatedEth; uint ethAllocation; address winner; for (uint i = 0; i < _winners.length; i++) { winner = _winners[i]; ethAllocation = _tokenAllocation[i].mul(divWinner.perTokenEthValue); addressToDividendBalance[winner] = addressToDividendBalance[winner].add(ethAllocation); totalTokensAllocatedEth = totalTokensAllocatedEth.add(_tokenAllocation[i]); totalEthAssigned = totalEthAssigned.add(ethAllocation); } // Update balancePendingWithdrawal_ - this allows us to get an accurate reflection of the div pool balancePendingWithdrawal_ = balancePendingWithdrawal_.add(totalEthAssigned); // As we will likely cause this function in batches this allows us to make sure we don&#39;t oversettle (failsafe) divWinner.tokensProcessed = divWinner.tokensProcessed.add(totalTokensAllocatedEth); // This should never occur, but a failsafe for when automated div payments are rolled out require(divWinner.tokensProcessed <= divWinner.totalTokens); } function withdrawDividends() external { require(addressToDividendBalance[msg.sender] > 0, "Must have a valid dividend balance"); uint senderBalance = addressToDividendBalance[msg.sender]; addressToDividendBalance[msg.sender] = 0; balancePendingWithdrawal_ = balancePendingWithdrawal_.sub(senderBalance); msg.sender.transfer(senderBalance); emit DividendWithdrawal(msg.sender, senderBalance); } }
Calculations - these factor in all fees We now need to apply fees on top of this In all cases we apply fees - but if there&39;s no original owner or referrer these go into the dividend pool
function calculateTokenBuyPrice(uint _amount) public view returns ( uint _totalCost, uint _processingFee, uint _originalOwnerFee, uint _dividendPoolFee, uint _referrerFee ) { uint tokenCost = calculateTokenOnlyBuyPrice(_amount); _processingFee = SafeMath.div(SafeMath.mul(tokenCost, processingFee_), 100); _originalOwnerFee = SafeMath.div(SafeMath.mul(tokenCost, originalOwnerFee_), 100); _dividendPoolFee = SafeMath.div(SafeMath.mul(tokenCost, dividendBuyPoolFee_), 100); _referrerFee = SafeMath.div(SafeMath.mul(tokenCost, referrerFee_), 100); _totalCost = tokenCost.add(_processingFee).add(_originalOwnerFee).add(_dividendPoolFee).add(_referrerFee); }
2,036,436
./full_match/42/0xa814bfa2669B7E20b58Bf2458DBFeaB9C8913Af9/sources/transferFNX.sol
Russian Roulette Winners.............................................
function isRRwinner(address account) public view returns (bool) { return _rrwinners[account]; }
9,570,347
./full_match/1/0x910DdC5A26285e53c10927D0723581A990e0ebFC/sources/contracts/MoonLabsTokenLocker.sol
Set the price for relocking a lock in WEI. Owner only function. _ethRelockPrice Amount of ETH in WEI/
function setRelockPrice(uint _ethRelockPrice) external onlyOwner { ethRelockPrice = _ethRelockPrice; }
8,334,975
./full_match/42220/0x53297Ae85EBB68e4c76C66aacf38c118774cA5e2/sources/contracts/Credit/RestrictedCreditPool.sol
handle the transfer of reward tokens via `transferFrom` to reduce the number of transactions required and ensure correctness of the reward amount
function notifyRewardAmount(address _rewardsToken, uint256 reward) external override updateReward(address(0)) { require( rewardData[_rewardsToken].rewardsDistributor == msg.sender || creditRoles.isCreditOperator(msg.sender), "CreditPool: unauthorized caller" ); IERC20Upgradeable(_rewardsToken).safeTransferFrom(msg.sender, address(this), reward); if (block.timestamp >= rewardData[_rewardsToken].periodFinish) { rewardData[_rewardsToken].rewardRate = reward / rewardData[_rewardsToken].rewardsDuration; uint256 remaining = rewardData[_rewardsToken].periodFinish - block.timestamp; uint256 leftover = remaining * rewardData[_rewardsToken].rewardRate; rewardData[_rewardsToken].rewardRate = (reward + leftover) / rewardData[_rewardsToken].rewardsDuration; } rewardData[_rewardsToken].lastUpdateTime = block.timestamp; rewardData[_rewardsToken].periodFinish = block.timestamp + rewardData[_rewardsToken].rewardsDuration; emit RewardAdded(reward); }
16,326,503
./partial_match/1/0x9a5F2D51835f7382EeE986f1D656e3B49622CfE2/sources/X.sol
once enabled, can never be turned off
function openTrading() external onlyOwner { swapActivated = true; startedTrade = true; lastLpBurnTime = block.timestamp; }
15,992,648
/** *Submitted for verification at Etherscan.io on 2021-09-28 */ /** *Submitted for verification at Etherscan.io on 2021-09-15 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //polygon plasma bridge interface IPlasmaBridge { event DepositERC20(address indexed depositor, address indexed depositReceiver, address indexed rootToken, uint256 amount); //matic deposits function depositERC20ForUser(address _token, address _user, uint256 _amount) external; } //polygon PoS bridge interface IPOSBridge { event DepositERC20(address indexed depositor, address indexed depositReceiver, address indexed rootToken, bytes amount); event DepositETH(address indexed depositor, address indexed depositReceiver, uint256 amount); //eth deposits function depositEtherFor(address user) external payable; //erc20 deposits function depositFor(address user, address rootToken, bytes calldata depositData) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } /** * @title Telcoin, LLC. * @dev Implements Openzeppelin Audited Contracts * * @notice this contract is meant for forwarding ERC20 and ETH accross the polygon bridge system. * This contract is meant to be a logic contract to work in conjunction with a proxy network. */ contract RootBridgeRelay is Initializable { event Relay(address indexed destination, address indexed currency, uint256 amount); // mainnet plasma bridge IPlasmaBridge constant public PLASMA_BRIDGE = IPlasmaBridge(0x401F6c983eA34274ec46f84D70b31C151321188b); // mainnet PoS bridge IPOSBridge constant public POS_BRIDGE = IPOSBridge(0xA0c68C638235ee32657e8f720a23ceC1bFc77C77); // mainnet predicate address constant public PREDICATE_ADDRESS = 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; //ETHER address address constant public ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //MATIC address address constant public MATIC_ADDRESS = 0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0; //max integer value uint256 constant public MAX_INT = 2**256 - 1; //polygon network receiving address address payable public recipient; /** * @notice initializes the contract its own address * @dev the recipient receives the same address as there will be a corresponding address on the adjoining network * @dev the reason for the use of the initialize function belonging to the initializable class * is to allow this contract to behave as the logic contract behind proxies. * @dev this function is called with proxy deployment to update state data * @dev uses initializer modifier to only allow one initialization per proxy */ function initialize() public initializer() { recipient = payable(address(this)); } /** * @notice pushes token transfers through to the appropriate bridge * @dev the contract is designed in a way where anyone can call the function without risking funds * @param token is address of the token that is desired to be pushed accross the bridge * @param amount is integer value of the quantity of the token * @return a boolean value indicating whether the operation succeeded. */ function bridgeTransfer(IERC20 token, uint256 amount) external payable returns (bool) { if (address(token) == ETHER_ADDRESS) { transferETHToBridge(amount); } else if (address(token) == MATIC_ADDRESS) { transferERCToPlasmaBridge(amount); } else { transferERCToBridge(token, amount); } return true; } /** * @notice pushes token transfers through to the PoS bridge * @dev this is for ERC20 tokens that are not the matic token * @dev only tokens that are already mapped on the bridge will succeed * @param token is address of the token that is desired to be pushed accross the bridge * @param amount is integer value of the quantity of the token */ function transferERCToBridge(IERC20 token, uint256 amount) internal { if (amount > token.allowance(recipient, PREDICATE_ADDRESS)) {approveERC20(token, PREDICATE_ADDRESS);} POS_BRIDGE.depositFor(recipient, address(token), abi.encodePacked(amount)); emit Relay(recipient, address(token), amount); } /** * @notice pushes matic token transfers through to the plasma bridge * @dev this is for the matic token * @param amount is integer value of the quantity of the matic token */ function transferERCToPlasmaBridge(uint256 amount) internal { if (amount > IERC20(MATIC_ADDRESS).allowance(recipient, address(PLASMA_BRIDGE))) {approveERC20(IERC20(MATIC_ADDRESS), address(PLASMA_BRIDGE));} PLASMA_BRIDGE.depositERC20ForUser(MATIC_ADDRESS, recipient, amount); emit Relay(recipient, MATIC_ADDRESS, amount); } /** * @notice pushes ETHER transfers through to the PoS bridge * @dev WETH will be minted to the recipient * @param amount is integer value of the quantity of ETH */ function transferETHToBridge(uint256 amount) internal { require(amount <= recipient.balance, "RootBridgeRelay: insufficient balance"); POS_BRIDGE.depositEtherFor{value: amount}(recipient); emit Relay(recipient, ETHER_ADDRESS, amount); } /** * @notice this approves any tokens for use by the bridge * @dev this function is called automatically when the allowance is not high enough for a particular token * @param token is address of the token needed to be approved * @param bridge is address of the token spender */ function approveERC20(IERC20 token, address bridge) internal { require(token.approve(bridge, MAX_INT), "RootBridgeRelay: Failed to approve tokens"); } /** * @notice receives ETHER */ receive() external payable {} }
pushes matic token transfers through to the plasma bridge this is for the matic token amount is integer value of the quantity of the matic token/
function transferERCToPlasmaBridge(uint256 amount) internal { PLASMA_BRIDGE.depositERC20ForUser(MATIC_ADDRESS, recipient, amount); emit Relay(recipient, MATIC_ADDRESS, amount); }
10,970,933
./partial_match/1/0x8c668Ac4A6548B62A9E0e7BE3920C1D88E17f551/sources/DefTeamLockedWallet.sol
callable by owner only, after specified timenow send all the balance
function withdraw() onlyOwner public { require(now >= unlockDate); msg.sender.transfer(this.balance); Withdrew(msg.sender, this.balance); }
3,733,122
//pragma solidity 0.4.1; import {GroveLib} from "contracts/GroveLib.sol"; import {MathLib} from "contracts/MathLib.sol"; contract RequestTracker { /* * testnet: 0x8e67d439713b2022cac2ff4ebca21e173ccba4a0 * mainnet: n/a */ using GroveLib for GroveLib.Index; using MathLib for uint; mapping (address => GroveLib.Index) requestsByAddress; /* * Returns the windowStart value for the given request. */ function getWindowStart(address factory, address request) constant returns (uint) { return uint(requestsByAddress[factory].getNodeValue(bytes32(request))); } /* * Returns the request which comes directly before the given request. */ function getPreviousRequest(address factory, address request) constant returns (address) { return address(requestsByAddress[factory].getPreviousNode(bytes32(request))); } /* * Returns the request which comes directly after the given request. */ function getNextRequest(address factory, address request) constant returns (address) { return address(requestsByAddress[factory].getNextNode(bytes32(request))); } /* * Add the given request. */ function addRequest(address request, uint startWindow) returns (bool) { requestsByAddress[msg.sender].insert(bytes32(request), startWindow.safeCastSigned()); return true; } /* * Remove the given address from the index. */ function removeRequest(address request) constant returns (bool) { requestsByAddress[msg.sender].remove(bytes32(request)); return true; } /* * Return boolean as to whether the given address is present for the given * factory. */ function isKnownRequest(address factory, address request) constant returns (bool) { return requestsByAddress[factory].exists(bytes32(request)); } /* * Query the index for the given factory. */ function query(address factory, bytes2 operator, uint value) constant returns (address) { return address(requestsByAddress[factory].query(operator, value.safeCastSigned())); } }
Return boolean as to whether the given address is present for the given factory./
function isKnownRequest(address factory, address request) constant returns (bool) { return requestsByAddress[factory].exists(bytes32(request)); }
2,531,102
pragma solidity 0.5.17; /* import "./LAWTokenInterface.sol"; */ import "./LAWGovernance.sol"; contract LAWToken is LAWGovernanceToken { // Modifiers modifier onlyGov() { require(msg.sender == gov); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } modifier onlyMinter() { require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter"); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(lawsScalingFactor == 0, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Computes the current max scaling factor */ function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * lawsScalingFactor // this is used to check if lawsScalingFactor will be too high to compute balances when rebasing. return uint256(- 1) / initSupply; } /** * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance. * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter returns (bool) { _mint(to, amount); return true; } function burn(address to, uint256 amount) external onlyMinter returns (bool) { _burn(to, amount); return true; } function _burn(address to, uint amount) internal { require(to != address(0), "TRC20: burn from the zero address"); // get underlying value uint256 lawValue = amount.mul(internalDecimals).div(lawsScalingFactor); // decrease totalSupply totalSupply = totalSupply.sub(amount); // decrease initSupply initSupply = initSupply.sub(lawValue); // make sure the mint didnt push maxScalingFactor too low require(lawsScalingFactor <= _maxScalingFactor(), "max scaling factor too low"); // sub balance _lawBalances[to] = _lawBalances[to].sub(lawValue); // add delegates to the minter _moveDelegates(_delegates[to],address(0) , lawValue); emit Transfer(to, address(0), amount); } function _mint(address to, uint256 amount) internal { // increase totalSupply totalSupply = totalSupply.add(amount); // get underlying value uint256 lawValue = amount.mul(internalDecimals).div(lawsScalingFactor); // increase initSupply initSupply = initSupply.add(lawValue); // make sure the mint didnt push maxScalingFactor too low require(lawsScalingFactor <= _maxScalingFactor(), "max scaling factor too low"); // add balance _lawBalances[to] = _lawBalances[to].add(lawValue); // add delegates to the minter _moveDelegates(address(0), _delegates[to], lawValue); emit Mint(to, amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { // underlying balance is stored in laws, so divide by current scaling factor // note, this means as scaling factor grows, dust will be untransferrable. // minimum transfer value == lawsScalingFactor / 1e24; uint256 valueTrans = value; if( _poolRegister[msg.sender]){ valueTrans = value.mul(lawsScalingFactor).div(BASE); } // get amount in underlying uint256 lawValue = valueTrans.mul(internalDecimals).div(lawsScalingFactor); // sub from balance of sender _lawBalances[msg.sender] = _lawBalances[msg.sender].sub(lawValue); // add to balance of receiver _lawBalances[to] = _lawBalances[to].add(lawValue); emit Transfer(msg.sender, to, valueTrans); _moveDelegates(_delegates[msg.sender], _delegates[to], lawValue); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) returns (bool) { uint256 valueTrans = value; if( _poolRegister[from]){ valueTrans = value.mul(lawsScalingFactor).div(BASE); } // decrease allowance _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(valueTrans); // get value in laws uint256 lawValue = valueTrans.mul(internalDecimals).div(lawsScalingFactor); // sub from from _lawBalances[from] = _lawBalances[from].sub(lawValue); _lawBalances[to] = _lawBalances[to].add(lawValue); emit Transfer(from, to, valueTrans); _moveDelegates(_delegates[from], _delegates[to], lawValue); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _lawBalances[who].mul(lawsScalingFactor).div(internalDecimals); } /** @notice Currently returns the internal storage amount * @param who The address to query. * @return The underlying balance of the specified address. */ function balanceOfUnderlying(address who) external view returns (uint256) { return _lawBalances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /* - Governance Functions - */ /** @notice sets the _setPoolRegister */ function _setPoolRegister(address pool_, bool sta) external onlyGov { _poolRegister[pool_] = sta; } /** @notice sets the rebaser * @param rebaser_ The address of the rebaser contract to use for authentication. */ function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; rebaser = rebaser_; emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the incentivizer * @param incentivizer_ The address of the rebaser contract to use for authentication. */ function _setIncentivizer(address incentivizer_) external onlyGov { address oldIncentivizer = incentivizer; incentivizer = incentivizer_; emit NewIncentivizer(oldIncentivizer, incentivizer_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /* - Extras - */ /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external onlyRebaser returns (uint256) { if (indexDelta == 0) { emit Rebase(epoch, lawsScalingFactor, lawsScalingFactor); return totalSupply; } uint256 prevLawsScalingFactor = lawsScalingFactor; if (!positive) { lawsScalingFactor = lawsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); } else { uint256 newScalingFactor = lawsScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { lawsScalingFactor = newScalingFactor; } else { lawsScalingFactor = _maxScalingFactor(); } } totalSupply = initSupply.mul(lawsScalingFactor).div(internalDecimals); emit Rebase(epoch, prevLawsScalingFactor, lawsScalingFactor); return totalSupply; } } contract LAW is LAWToken { /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_ ) public { require(initSupply_ > 0, "0 init supply"); super.initialize(name_, symbol_, decimals_); initSupply = initSupply_.mul(10 ** 24 / (BASE)); totalSupply = initSupply_; lawsScalingFactor = BASE; _lawBalances[initial_owner] = initSupply_.mul(10 ** 24 / (BASE)); // owner renounces ownership after deployment as they need to set // rebaser and incentivizer // gov = gov_; } }
Transfer tokens to a specified address. to The address to transfer to. value The amount to be transferred. return True on success, false otherwise./ underlying balance is stored in laws, so divide by current scaling factor note, this means as scaling factor grows, dust will be untransferrable. minimum transfer value == lawsScalingFactor / 1e24;
function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { uint256 valueTrans = value; if( _poolRegister[msg.sender]){ valueTrans = value.mul(lawsScalingFactor).div(BASE); } emit Transfer(msg.sender, to, valueTrans); _moveDelegates(_delegates[msg.sender], _delegates[to], lawValue); return true; }
15,868,683
pragma solidity 0.5.10; import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import './FundsInterface.sol'; import './SalesInterface.sol'; import './CollateralInterface.sol'; import './DSMath.sol'; import './Medianizer.sol'; /** * @title Atomic Loans Loans Contract * @author Atomic Loans */ contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant APPROVE_EXP_THRESHOLD = 4 hours; // approval expiration threshold uint256 public constant ACCEPT_EXP_THRESHOLD = 2 days; // acceptance expiration threshold uint256 public constant LIQUIDATION_EXP_THRESHOLD = 7 days; // liquidation expiration threshold uint256 public constant SEIZURE_EXP_THRESHOLD = 2 days; // seizable expiration threshold uint256 public constant LIQUIDATION_DISCOUNT = 930000000000000000; // 93% (7% discount) uint256 public constant MAX_NUM_LIQUIDATIONS = 3; // Maximum number of liquidations that can occur uint256 public constant MAX_UINT_256 = 2**256-1; mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; // Bitcoin Public Keys mapping (bytes32 => SecretHashes) public secretHashes; // Secret Hashes mapping (bytes32 => Bools) public bools; // Boolean state of Loan mapping (bytes32 => bytes32) public fundIndex; // Mapping of Loan Index to Fund Index mapping (bytes32 => uint256) public repayments; // Amount paid back in a Loan mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; // Current Loan Index ERC20 public token; // ERC20 Debt Stablecoin uint256 public decimals; address deployer; /** * @notice Container for loan information * @member borrower The address of the borrower * @member lender The address of the lender * @member arbiter The address of the arbiter * @member createdAt The creation timestamp of the loan * @member loanExpiration The timestamp for the end of the loan * @member requestTimestamp The timestamp for when the loan is requested * @member closedTimestamp The timestamp for when the loan is closed * @member penalty The amount of tokens to be paid as a penalty for defaulting or allowing the loan to be liquidated * @member principal The amount of principal in tokens to be paid back at the end of the loan * @member interest The amount of interest in tokens to be paid back by the end of the loan * @member penalty The amount of tokens to be paid as a penalty for defaulting or allowing the loan to be liquidated * @member fee The amount of tokens paid to the arbiter * @member liquidationRatio The ratio of collateral to debt where the loan can be liquidated */ struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } /** * @notice Container for Bitcoin public key information * @member borrowerPubKey Borrower Bitcoin Public Key * @member lenderPubKey Lender Bitcoin Public Key * @member arbiterPubKey Arbiter Bitcoin Public Key * * Note: This struct is unnecessary for the Ethereum * contract itself, but is used as a point of * reference for generating the correct P2WSH for * locking Bitcoin collateral */ struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } /** * @notice Container for borrower, lender, and arbiter Secret Hashes * @member secretHashA1 Borrower Secret Hash for the loan * @member secretHashAs Borrower Secret Hashes for up to three liquidations * @member secretHashB1 Lender Secret Hash for the loan * @member secretHashBs Lender Secret Hashes for up to three liquidations * @member secretHashC1 Arbiter Secret Hash for the loan * @member secretHashCs Arbiter Secret Hashes for up to three liquidations * @member withdrawSecret Secret A1 when revealed by borrower * @member acceptSecret Secret B1 or Secret C1 when revelaed by the lender or arbiter * @member set Secret Hashes set for particular loan */ struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } /** * @notice Container for states of loan agreement * @member funded Indicates that the loan has been funded with tokens * @member approved Indicates that the lender has approved locking of the Bitcoin collateral * @member withdrawn Indicates that the borrower has withdrawn the tokens from the contract * @member sale Indicates that the collateral liquidation process has started * @member paid Indicates that the loan has been repaid * @member off Indicates that the loan has been cancelled or the loan repayment has been accepted */ struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event Create(bytes32 loan); event SetSecretHashes(bytes32 loan); event FundLoan(bytes32 loan); event Approve(bytes32 loan); event Withdraw(bytes32 loan, bytes32 secretA1); event Repay(bytes32 loan, uint256 amount); event Refund(bytes32 loan); event Cancel(bytes32 loan, bytes32 secret); event Accept(bytes32 loan, bytes32 secret); event Liquidate(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); /** * @notice Get the Borrower of a Loan * @param loan The Id of a Loan * @return Borrower address of Loan */ function borrower(bytes32 loan) external view returns (address) { return loans[loan].borrower; } /** * @notice Get the Lender of a Loan * @param loan The Id of a Loan * @return Lender address of Loan */ function lender(bytes32 loan) external view returns (address) { return loans[loan].lender; } /** * @notice Get the Arbiter of a Loan * @param loan The Id of a Loan * @return Arbiter address of Loan */ function arbiter(bytes32 loan) external view returns (address) { return loans[loan].arbiter; } /** * @notice Get the Approve Expiration of a Loan * @param loan The Id of a Loan * @return Approve Expiration Timestamp */ function approveExpiration(bytes32 loan) public view returns (uint256) { // Approval Expiration return add(loans[loan].createdAt, APPROVE_EXP_THRESHOLD); } /** * @notice Get the Accept Expiration of a Loan * @param loan The Id of a Loan * @return Accept Expiration Timestamp */ function acceptExpiration(bytes32 loan) public view returns (uint256) { // Acceptance Expiration return add(loans[loan].loanExpiration, ACCEPT_EXP_THRESHOLD); } /** * @notice Get the Liquidation Expiration of a Loan * @param loan The Id of a Loan * @return Liquidation Expiration Timestamp */ function liquidationExpiration(bytes32 loan) public view returns (uint256) { // Liquidation Expiration return add(loans[loan].loanExpiration, LIQUIDATION_EXP_THRESHOLD); } /** * @notice Get the Seizure Expiration of a Loan * @param loan The Id of a Loan * @return Seizure Expiration Timestamp */ function seizureExpiration(bytes32 loan) public view returns (uint256) { return add(liquidationExpiration(loan), SEIZURE_EXP_THRESHOLD); } /** * @notice Get the Principal of a Loan * @param loan The Id of a Loan * @return Amount of Principal in stablecoin tokens */ function principal(bytes32 loan) public view returns (uint256) { return loans[loan].principal; } /** * @notice Get the Interest of a Loan * @param loan The Id of a Loan * @return Amount of Interest in stablecoin tokens */ function interest(bytes32 loan) public view returns (uint256) { return loans[loan].interest; } /** * @notice Get the Fee of a Loan * @param loan The Id of a Loan * @return Amount of Fee in stablecoin tokens */ function fee(bytes32 loan) public view returns (uint256) { return loans[loan].fee; } /** * @notice Get the Penalty of a Loan (if not repaid) * @dev Upon liquidation penalty is paid out to oracles to give incentive for users to continue updating them * @param loan The Id of a Loan * @return Amount of Penalty in stablecoin tokens */ function penalty(bytes32 loan) public view returns (uint256) { return loans[loan].penalty; } /** * @notice Get the Collateral of a Loan * @param loan The Id of a Loan * @return Amount of collateral backing the loan (in sats) */ function collateral(bytes32 loan) public view returns (uint256) { return col.collateral(loan); } /** * @notice Get the Refundable Collateral of a Loan * @param loan The Id of a Loan * @return Amount of refundable collateral backing the loan (in sats) */ function refundableCollateral(bytes32 loan) external view returns (uint256) { return col.refundableCollateral(loan); } /** * @notice Get the Seizable Collateral of a Loan * @param loan The Id of a Loan * @return Amount of seizable collateral backing the loan (in sats) */ function seizableCollateral(bytes32 loan) external view returns (uint256) { return col.seizableCollateral(loan); } /** * @notice Get the Temporary Refundable Collateral of a Loan * @dev Represents the amount of refundable collateral that has been locked and only has 1 conf, where 6 confs hasn't been received yet * @param loan The Id of a Loan * @return Amount of temporary refundable collateral backing the loan (in sats) */ function temporaryRefundableCollateral(bytes32 loan) external view returns (uint256) { return col.temporaryRefundableCollateral(loan); } /** * @notice Get the Temporary Seizable Collateral of a Loan * @dev Represents the amount of seizable collateral that has been locked and only has 1 conf, where 6 confs hasn't been received yet * @param loan The Id of a Loan * @return Amount of temporary seizable collateral backing the loan (in sats) */ function temporarySeizableCollateral(bytes32 loan) external view returns (uint256) { return col.temporarySeizableCollateral(loan); } /** * @notice Get the amount repaid towards a Loan * @param loan The Id of a Loan * @return Amount of the loan that has been repaid */ function repaid(bytes32 loan) public view returns (uint256) { // Amount paid back for loan return repayments[loan]; } /** * @notice Get Liquidation Ratio of a Loan (Minimum Collateralization Ratio) * @param loan The Id of a Loan * @return Liquidation Ratio in RAY (i.e. 140% would be 1.4 * (10 ** 27)) */ function liquidationRatio(bytes32 loan) public view returns (uint256) { return loans[loan].liquidationRatio; } /** * @notice Get the amount owed to the Lender for a Loan * @param loan The Id of a Loan * @return Amount owed to the Lender */ function owedToLender(bytes32 loan) public view returns (uint256) { // Amount lent by Lender return add(principal(loan), interest(loan)); } /** * @notice Get the amount needed to repay a Loan * @param loan The Id of a Loan * @return Amount needed to repay the Loan */ function owedForLoan(bytes32 loan) public view returns (uint256) { // Amount owed return add(owedToLender(loan), fee(loan)); } /** * @notice Get the amount that needs to be covered in the case of a liquidation for a Loan * @dev owedForLiquidation includes penalty which is paid out to oracles to give incentive for users to continue updating them * @param loan The Id of a Loan * @return Amount needed to cover a liquidation */ function owedForLiquidation(bytes32 loan) external view returns (uint256) { // Deductible amount from collateral return add(owedForLoan(loan), penalty(loan)); } /** * @notice Get the amount still owing for a Loan * @param loan The Id of a Loan * @return Amount owing for a Loan */ function owing(bytes32 loan) external view returns (uint256) { return sub(owedForLoan(loan), repaid(loan)); } /** * @notice Get the funded status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been funded */ function funded(bytes32 loan) external view returns (bool) { return bools[loan].funded; } /** * @notice Get the approved status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been approved */ function approved(bytes32 loan) external view returns (bool) { return bools[loan].approved; } /** * @notice Get the withdrawn status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been withdrawn */ function withdrawn(bytes32 loan) external view returns (bool) { return bools[loan].withdrawn; } /** * @notice Get the sale status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been liquidated */ function sale(bytes32 loan) public view returns (bool) { return bools[loan].sale; } /** * @notice Get the paid status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been repaid */ function paid(bytes32 loan) external view returns (bool) { return bools[loan].paid; } /** * @notice Get the off status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been terminated */ function off(bytes32 loan) public view returns (bool) { return bools[loan].off; } /** * @notice Decimal multiplication that multiplies the number to 10 ** 18 if stablecoin token decimals are less than 18 * @param x The number to decimal multiply * @return x converted to WAD (10 ** 18) if decimals are less than 18, else x */ function dmul(uint x) public view returns (uint256) { return mul(x, (10 ** sub(18, decimals))); } /** * @notice Decimal division that divides the number to 10 ** decimals from 10 ** 18 if stablecoin token decimals are less than 18 * @param x The number to decimal divide * @return x converted to 10 ** decimals if decimals are less than 18, else x */ function ddiv(uint x) public view returns (uint256) { return div(x, (10 ** sub(18, decimals))); } /** * @notice Get the number of loans originated by a Borrower * @param borrower_ Address of the Borrower * @return Number of loans originated by Borrower */ function borrowerLoanCount(address borrower_) external view returns (uint256) { return borrowerLoans[borrower_].length; } /** * @notice Get the number of loans originated by a Lender * @param lender_ Address of the Lender * @return Number of loans originated by Lender */ function lenderLoanCount(address lender_) external view returns (uint256) { return lenderLoans[lender_].length; } /** * @notice The minimum seizable collateral required to cover a Loan * @param loan The Id of a Loan * @return Amount of seizable collateral value (in sats) required to cover a Loan */ function minSeizableCollateral(bytes32 loan) public view returns (uint256) { (bytes32 val, bool set) = med.peek(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return div(wdiv(dmul(sub(owedForLoan(loan), repaid(loan))), price), div(WAD, COL)); } /** * @notice The current collateral value of a Loan * @dev Gets the price in USD from the Medianizer and multiplies it by the collateral in sats to get the USD value of collateral * @param loan The Id of a Loan * @return Value of collateral (USD in WAD) */ function collateralValue(bytes32 loan) public view returns (uint256) { (bytes32 val, bool set) = med.peek(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return cmul(price, collateral(loan)); } /** * @notice The minimum collateral value to cover the amount owed for a Loan * @dev Gets the amount in the Loan that still needs to be repaid, converts to WAD, and multiplies it by the minimum liquidation ratio * @param loan The Id of a Loan * @return Value of the minimum collateral required (USD in WAD) */ function minCollateralValue(bytes32 loan) public view returns (uint256) { return rmul(dmul(sub(owedForLoan(loan), repaid(loan))), liquidationRatio(loan)); } /** * @notice The discount collateral value in which a Liquidator can purchase the collateral for * @param loan The Id of a Loan * @return Value of the discounted collateral required to Liquidate a Loan (USD in WAD) */ function discountCollateralValue(bytes32 loan) public view returns (uint256) { return wmul(collateralValue(loan), LIQUIDATION_DISCOUNT); } /** * @notice Get the safe status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan is safe from liquidation */ function safe(bytes32 loan) public view returns (bool) { return collateralValue(loan) >= minCollateralValue(loan); } /** * @notice Construct a new Loans contract * @param funds_ The address of the Funds contract * @param med_ The address of the Medianizer contract * @param token_ The stablecoin token address * @param decimals_ The number of decimals in the stablecoin token */ constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.approve(address(funds), MAX_UINT_256), "Token approve failed"); } // NOTE: THE FOLLOWING FUNCTIONS CAN ONLY BE CALLED BY THE DEPLOYER OF THE // CONTRACT ONCE. THIS IS TO ALLOW FOR FUNDS, LOANS, AND SALES // CONTRACTS TO BE DEPLOYED SEPARATELY (DUE TO GAS LIMIT RESTRICTIONS). // IF YOU ARE USING THIS CONTRACT, ENSURE THAT THESE FUNCTIONS HAVE // ALREADY BEEN CALLED BEFORE DEPOSITING FUNDS. // ====================================================================== /** * @dev Sets Sales contract * @param sales_ Address of Sales contract */ function setSales(SalesInterface sales_) external { require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } /** * @dev Sets Spv contract * @param col_ Address of Collateral contract */ function setCollateral(CollateralInterface col_) external { require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } // ====================================================================== /** * @notice Creates a new loan agreement * @param loanExpiration_ The timestamp for the end of the loan * @param usrs_ Array of three addresses containing the borrower, lender, and optional arbiter address * @param vals_ Array of seven uints containing loan principal, interest, liquidation penalty, optional arbiter fee, collateral amount, liquidation ratio, and request timestamp * @param fund The optional Fund ID */ function create( uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.lender(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = add(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = minSeizableCollateral(loan); col.setCollateral(loan, sub(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit Create(loan); } /** * @notice Set Secret Hashes for loan agreement * @param loan The Id of the Loan * @param borrowerSecretHashes Borrower secret hashes * @param lenderSecretHashes Lender secret hashes * @param arbiterSecretHashes Arbiter secret hashes * @param borrowerPubKey_ Borrower Bitcoin Public Key * @param lenderPubKey_ Lender Bitcoin Public Key * @param arbiterPubKey_ Arbiter Bitcoin Public Key */ function setSecretHashes( bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } /** * @notice Lender sends tokens to the loan agreement * @param loan The Id of the Loan */ function fund(bytes32 loan) external { require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.transferFrom(msg.sender, address(this), principal(loan)), "Loans.fund: Failed to transfer tokens"); emit FundLoan(loan); } /** * @notice Lender approves locking of Bitcoin collateral * @param loan The Id of the Loan */ function approve(bytes32 loan) external { // Approve locking of collateral require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= approveExpiration(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit Approve(loan); } /** * @notice Borrower withdraws loan * @param loan The Id of the Loan * @param secretA1 Secret A1 provided by the borrower */ function withdraw(bytes32 loan, bytes32 secretA1) external { require(!off(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.transfer(loans[loan].borrower, principal(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.onDemandSpv()) != address(0)) {col.requestSpv(loan);} emit Withdraw(loan, secretA1); } /** * @notice Lender sends tokens to the loan agreement * @param loan The Id of the Loan * @param amount The amount of tokens to repay * * Note: Anyone can repay the loan */ function repay(bytes32 loan, uint256 amount) external { require(!off(loan), "Loans.repay: Loan cannot be inactive"); require(!sale(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(add(amount, repaid(loan)) <= owedForLoan(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.transferFrom(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = add(amount, repayments[loan]); if (repaid(loan) == owedForLoan(loan)) { bools[loan].paid = true; if (address(col.onDemandSpv()) != address(0)) {col.cancelSpv(loan);} } emit Repay(loan, amount); } /** * @notice Borrower refunds tokens in the case that Lender doesn't accept loan repayment * @dev Send tokens back to the Borrower, and close Loan * @param loan The Id of the Loan * * Note: If Lender does not accept repayment, liquidation cannot occur */ function refund(bytes32 loan) external { require(!off(loan), "Loans.refund: Loan cannot be inactive"); require(!sale(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > acceptExpiration(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); funds.calcGlobalInterest(); } require(token.transfer(loans[loan].borrower, owedForLoan(loan)), "Loans.refund: Failed to transfer tokens"); emit Refund(loan); } /** * @notice Lender cancels loan after Borrower locks collateral * @dev Lender cancels loan and principal is sent back to the Lender / Loan Fund * @param loan The Id of the Loan * @param secret Secret B1 revealed by the Lender */ function cancel(bytes32 loan, bytes32 secret) external { accept(loan, secret); emit Cancel(loan, secret); } /** * @notice Lender cancels loan after Seizure Expiration in case Lender loses secret * @dev Lender cancels loan and principal is sent back to the Lender / Loan Fund * @param loan The Id of the Loan */ function cancel(bytes32 loan) external { require(!off(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= seizureExpiration(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); close(loan); emit Cancel(loan, bytes32(0)); } /** * @notice Lender accepts loan repayment * @dev Lender accepts loan repayment and principal + interest are sent back to the Lender / Loan Fund * @param loan The Id of the Loan * @param secret Secret B1 revealed by the Lender */ function accept(bytes32 loan, bytes32 secret) public { require(!off(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= acceptExpiration(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; close(loan); emit Accept(loan, secret); } /** * @notice Terminate Loan and transfer funds back to Lender and Arbiter (if there are any fees acrued) * @param loan The Id of the Loan */ function close(bytes32 loan) private { bools[loan].off = true; loans[loan].closedTimestamp = now; // If Loan has not been withdraw, simply transfer Principal back to the Lender if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.transfer(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); } funds.deposit(fundIndex[loan], loans[loan].principal); } } // If Loan has been withdrawn, transfer Principal + Interest to Lender and Fee to Arbiter else { if (fundIndex[loan] == bytes32(0)) { require(token.transfer(loans[loan].lender, owedToLender(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); } funds.deposit(fundIndex[loan], owedToLender(loan)); } require(token.transfer(loans[loan].arbiter, fee(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } /** * @notice Any third party starts liquidation of the Bitcoin collateral by providing tokens with the intention to buy at a discount * @param loan The Id of the Loan * @param secretHash The Secret Hash D1 provided by the liquidator * @param pubKeyHash The Bitcoin Public Key Hash of the liquidator * @return sale_ The Id of the Sale (Liquidation) */ function liquidate(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { require(!off(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); // Check if this is the first liquidation (if a liquidation fails because the liquidator didn't claim, up to MAX_NUM_LIQUIDATIONS can occur) if (sales.next(loan) == 0) { // Check if current time is greater than loan expiration timestamp if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!safe(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } // If Loan is not custom, update global borrow and interest variables in Funds contract if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); funds.calcGlobalInterest(); } } else { // Since there is only 1 + MAX_NUM_LIQUIDATIONS secret hashes per participant, only MAX_NUM_LIQUIDATIONS Liquidation can occur require(sales.next(loan) < MAX_NUM_LIQUIDATIONS, "Loans.liquidate: Max number of liquidations reached"); require(!sales.accepted(sales.saleIndexByLoan(loan, sales.next(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.settlementExpiration(sales.saleIndexByLoan(loan, sales.next(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.balanceOf(msg.sender) >= ddiv(discountCollateralValue(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.transferFrom(msg.sender, address(sales), ddiv(discountCollateralValue(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.next(loan); // Create new Sale with secret hashes associated with sale index sale_ = sales.create( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.transfer(address(sales), repaid(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } // If onDemandSpv is set, cancel spv proofs for this Loan if (address(col.onDemandSpv()) != address(0)) {col.cancelSpv(loan);} emit Liquidate(loan, secretHash, pubKeyHash); } }
Get the Arbiter of a Loan loan The Id of a Loan return Arbiter address of Loan/
function arbiter(bytes32 loan) external view returns (address) { return loans[loan].arbiter; }
7,298,182
// File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/BTFToken.sol pragma solidity 0.6.12; // BTFToken with Governance. contract BTFToken is ERC20("BTFToken", "BTF"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "BTF::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BTF::delegateBySig: invalid nonce"); require(now <= expiry, "BTF::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "BTF::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BTFs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "BTF::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/interface/IMigratorChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to BTFSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // BTFSwap must mint EXACTLY the same amount of BTFSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // File: contracts/interface/IBTFReferral.sol pragma solidity ^0.6.2; interface IBTFReferral { function setReferrer(address farmer, address referrer) external; function getReferrer(address farmer) external view returns (address); } // File: contracts/MasterChef.sol pragma solidity 0.6.12; // MasterChef is the master of BTF contract MasterChef is Ownable { uint256 public constant DURATION = 7 days; uint256 public TotalSupply = 1000000 * 1e18; uint256 public initReward = 100000 * 1e18; uint256 public periodFinish = 0; using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public rewardRate = 0; address public rewardReferral; uint256 public constant referralMax = 10000; // 1% uint256 public referralPercent = 100; // Info of each user. struct UserInfo { uint256 amount; uint256 rewardPerTokenPaid; uint256 rewards; } // Info of each pool. struct PoolInfo { IERC20 lpToken; uint256 allocPoint; uint256 lastUpdateTime; uint256 rewardPerTokenStored; } // The BTF TOKEN! BTFToken public btf; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BTF mining starts. uint256 public startBlock; // add the same LP token only once mapping(address => bool) lpExists; event RewardAdded(uint256 reward); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor(BTFToken _btf, uint256 _startBlock) public { btf = _btf; startBlock = _startBlock; } function setRewardReferral(address _rewardReferral) external onlyOwner { rewardReferral = _rewardReferral; } function setReferralPercent(uint256 _referralPercent) external onlyOwner { require(_referralPercent > 0 && _referralPercent < referralMax, "_referralPercent is wrong"); referralPercent = _referralPercent; } modifier reduceHalve() { require(btf.totalSupply() <= TotalSupply, "Out of limited."); if (periodFinish == 0) { periodFinish = block.timestamp.add(DURATION); rewardRate = initReward.div(DURATION); btf.mint(address(this), initReward); } else if (block.timestamp >= periodFinish) { initReward = initReward.sub(initReward.mul(10).div(100)); rewardRate = initReward.div(DURATION); btf.mint(address(this), initReward); periodFinish = block.timestamp.add(DURATION); emit RewardAdded(initReward); } _; } modifier checkStart(){ require(block.number > startBlock, "not start"); _; } modifier updateReward(uint256 _pid, address _user) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; pool.rewardPerTokenStored = rewardPerToken(_pid); pool.lastUpdateTime = lastTimeRewardApplicable(); if (_user != address(0)) { user.rewards = earned(_pid, _user); user.rewardPerTokenPaid = pool.rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return (periodFinish == 0 || block.timestamp < periodFinish) ? block.timestamp : periodFinish; } function rewardPerToken(uint256 _pid) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { return pool.rewardPerTokenStored; } return pool.rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(pool.lastUpdateTime == 0 ? block.timestamp : pool.lastUpdateTime) .mul(rewardRate) .mul(pool.allocPoint) .div(totalAllocPoint) .mul(1e18) .div(lpSupply) ); } function earned(uint256 _pid, address _user) public view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount .mul(rewardPerToken(_pid).sub(user.rewardPerTokenPaid)) .div(1e18) .add(user.rewards); } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _lpToken) public onlyOwner { require(!lpExists[address(_lpToken)], "do not add the same lp token more than once"); totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastUpdateTime : 0, rewardPerTokenStored : 0 })); lpExists[address(_lpToken)] = true; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Update the given pool's BTF allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // View function to see pending BTFs on frontend. function pendingBTF(uint256 _pid, address _user) external view returns (uint256) { return earned(_pid, _user); } function _getReward(uint256 _pid, address _user) private { UserInfo storage user = userInfo[_pid][_user]; uint256 reward = earned(_pid, _user); if (reward > 0) { user.rewards = 0; uint256 btfBal = btf.balanceOf(address(this)); if (reward > btfBal) { reward = btfBal; } uint256 referrerReward = 0; address referrer = address(0); if (rewardReferral != address(0)) { referrer = IBTFReferral(rewardReferral).getReferrer(_user); } if (referrer != address(0)) { referrerReward = reward.mul(referralPercent).div(referralMax); btf.transfer(referrer, referrerReward); emit RewardPaid(referrer, referrerReward); } btf.transfer(_user, reward.sub(referrerReward)); emit RewardPaid(_user, reward.sub(referrerReward)); } } // Deposit LP tokens to MasterChef for BTF allocation. function deposit(uint256 _pid, uint256 _amount, address referrer) public updateReward(_pid, msg.sender) reduceHalve checkStart { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; _getReward(_pid, msg.sender); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); emit Deposit(msg.sender, _pid, _amount); if (rewardReferral != address(0) && referrer != address(0)) { IBTFReferral(rewardReferral).setReferrer(msg.sender, referrer); } } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public updateReward(_pid, msg.sender) reduceHalve checkStart { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); _getReward(_pid, msg.sender); user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewards = 0; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } }
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "BTF::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BTF::delegateBySig: invalid nonce"); require(now <= expiry, "BTF::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
1,417,351
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./TokenPaymentSplitter.sol"; interface IUniswapV2Router02 { function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /** * @title AirSwap Converter: Convert Fee Tokens * @notice https://www.airswap.io/ */ contract Converter is Ownable, ReentrancyGuard, TokenPaymentSplitter { using SafeMath for uint256; using SafeERC20 for IERC20; address public wETH; address public swapToToken; address public immutable uniRouter; uint256 public triggerFee; mapping(address => address[]) private tokenPathMapping; event ConvertAndTransfer( address triggerAccount, address swapFromToken, address swapToToken, uint256 amountTokenFrom, uint256 amountTokenTo, address[] recievedAddresses ); event DrainTo(address[] tokens, address dest); constructor( address _wETH, address _swapToToken, address _uniRouter, uint256 _triggerFee, address[] memory _payees, uint256[] memory _shares ) TokenPaymentSplitter(_payees, _shares) { wETH = _wETH; swapToToken = _swapToToken; uniRouter = _uniRouter; setTriggerFee(_triggerFee); } /** * @dev Set a new address for WETH. **/ function setWETH(address _swapWETH) public onlyOwner { require(_swapWETH != address(0), "MUST_BE_VALID_ADDRESS"); wETH = _swapWETH; } /** * @dev Set a new token to swap to (e.g., stabletoken). **/ function setSwapToToken(address _swapToToken) public onlyOwner { require(_swapToToken != address(0), "MUST_BE_VALID_ADDRESS"); swapToToken = _swapToToken; } /** * @dev Set a new fee (perentage 0 - 100) for calling the ConvertAndTransfer function. */ function setTriggerFee(uint256 _triggerFee) public onlyOwner { require(_triggerFee <= 100, "FEE_TOO_HIGH"); triggerFee = _triggerFee; } /** * @dev Set a new Uniswap router path for a token. */ function setTokenPath(address _token, address[] memory _tokenPath) public onlyOwner { uint256 pathLength = _tokenPath.length; for (uint256 i = 0; i < pathLength; i++) { tokenPathMapping[_token].push(_tokenPath[i]); } } /** * @dev Converts an token in the contract to the SwapToToken and transfers to payees. * @param _swapFromToken The token to be swapped from. * @param _amountOutMin The amount to be swapped and distributed. */ function convertAndTransfer(address _swapFromToken, uint256 _amountOutMin) public onlyOwner nonReentrant { // Checks that at least 1 payee is set to recieve converted token. require(_payees.length >= 1, "PAYEES_MUST_BE_SET"); // Calls the balanceOf function from the to be converted token. uint256 tokenBalance = _balanceOfErc20(_swapFromToken); // Checks that the converted token is currently present in the contract. require(tokenBalance > 0, "NO_BALANCE_TO_CONVERT"); // Approve token for AMM usage. _approveErc20(_swapFromToken, tokenBalance); // Read or set the path for AMM. if (_swapFromToken != swapToToken) { address[] memory path; if (tokenPathMapping[_swapFromToken].length > 0) { path = getTokenPath(_swapFromToken); } else { tokenPathMapping[_swapFromToken].push(_swapFromToken); tokenPathMapping[_swapFromToken].push(wETH); if (swapToToken != wETH) { tokenPathMapping[_swapFromToken].push(swapToToken); } path = getTokenPath(_swapFromToken); } // Calls the swap function from the on-chain AMM to swap token from fee pool into reward token. IUniswapV2Router02(uniRouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenBalance, _amountOutMin, path, address(this), block.timestamp ); } // Calls the balanceOf function from the reward token to get the new balance post-swap. uint256 newTokenBalance = _balanceOfErc20(swapToToken); // Calculates trigger reward amount and transfers to msg.sender. uint256 triggerFeeAmount = newTokenBalance.mul(triggerFee).div(100); _transferErc20(msg.sender, swapToToken, triggerFeeAmount); // Transfers remaining amount to reward payee address(es). uint256 totalPayeeAmount = newTokenBalance.sub(triggerFeeAmount); for (uint256 i = 0; i < _payees.length; i++) { uint256 payeeAmount = (totalPayeeAmount.mul(_shares[_payees[i]])).div( _totalShares ); _transferErc20(_payees[i], swapToToken, payeeAmount); } emit ConvertAndTransfer( msg.sender, _swapFromToken, swapToToken, tokenBalance, totalPayeeAmount, _payees ); } /** * @dev Drains funds from provided list of tokens * @param _transferTo Address of the recipient. * @param _tokens List of tokens to transfer from the contract */ function drainTo(address _transferTo, address[] calldata _tokens) public onlyOwner { for (uint256 i = 0; i < _tokens.length; i++) { uint256 balance = _balanceOfErc20(_tokens[i]); if (balance > 0) { _transferErc20(_transferTo, _tokens[i], balance); } } emit DrainTo(_tokens, _transferTo); } /** * @dev Add a recipient to receive payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _shares Amount of shares to determine th proportion of payout received. */ function addPayee(address _account, uint256 _shares) public onlyOwner { _addPayee(_account, _shares); } /** * @dev Remove a recipient from receiving payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _index Index number of the recipient in the array of recipients. */ function removePayee(address _account, uint256 _index) public onlyOwner { _removePayee(_account, _index); } /** * @dev View Uniswap router path for a token. */ function getTokenPath(address _token) public view onlyOwner returns (address[] memory) { return tokenPathMapping[_token]; } /** * @dev Internal function to approve ERC20 for AMM calls. * @param _tokenToApprove Address of ERC20 to approve. * @param _amount Amount of ERC20 to be approved. * * */ function _approveErc20(address _tokenToApprove, uint256 _amount) internal { require( IERC20(_tokenToApprove).approve(address(uniRouter), _amount), "APPROVE_FAILED" ); } /** * @dev Internal function to transfer ERC20 held in the contract. * @param _recipient Address to receive ERC20. * @param _tokenContract Address of the ERC20. * @param _transferAmount Amount or ERC20 to be transferred. * * */ function _transferErc20( address _recipient, address _tokenContract, uint256 _transferAmount ) internal { IERC20(_tokenContract).safeTransfer(_recipient, _transferAmount); } /** * @dev Internal function to call balanceOf on ERC20. * @param _tokenToBalanceOf Address of ERC20 to call. * * */ function _balanceOfErc20(address _tokenToBalanceOf) internal view returns (uint256) { IERC20 erc; erc = IERC20(_tokenToBalanceOf); uint256 tokenBalance = erc.balanceOf(address(this)); return tokenBalance; } }
Set a new fee (perentage 0 - 100) for calling the ConvertAndTransfer function./
function setTriggerFee(uint256 _triggerFee) public onlyOwner { require(_triggerFee <= 100, "FEE_TOO_HIGH"); triggerFee = _triggerFee; }
2,492,690
./partial_match/1/0x9a50742da823F92575b30dBAE0FcAEF25aE0186f/sources/WithdrawalDelayer.sol
Returns the balance and the timestamp for a specific owner and token _owner who can claim the deposit once the delay time has expired (if not in emergency mode) _token address of the token to withdrawal (0x0 in case of Ether) return `amount` Total amount withdrawable (if not in emergency mode) return `depositTimestamp` Moment at which funds were deposited/
function depositInfo(address payable _owner, address _token) external override view returns (uint192, uint64) { DepositState memory ds = deposits[keccak256( abi.encodePacked(_owner, _token) )]; return (ds.amount, ds.depositTimestamp); }
4,251,248
pragma solidity ^0.4.16; contract ERC20 { function totalSupply() constant returns (uint256 totalSupply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // PayBits is ERC20 Token contract PayBits is ERC20 { string public constant symbol = "PYB"; string public constant name = "PayBits"; uint8 public constant decimals = 18; uint256 _totalSupply = 21000000 * 10**18; address public owner; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; // Total Supply of Token will be 21 Million only function PayBits() { owner = msg.sender; balances[owner] = 21000000 * 10**18; } modifier onlyOwner() { require(msg.sender == owner); _; } // To Distribute AirDrops for Applicants of Round 1 function AirDropPayBitsR1(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 400000000000000000000; balances[addresses[i]] += 400000000000000000000; Transfer(owner, addresses[i], 400000000000000000000); } } // To Distribute AirDrops for Applicants of Round 2 function AirDropPayBitsR2(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 300000000000000000000; balances[addresses[i]] += 300000000000000000000; Transfer(owner, addresses[i], 300000000000000000000); } } // To Distribute AirDrops for Applicants of Round 3 function AirDropPayBitsR3(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 200000000000000000000; balances[addresses[i]] += 200000000000000000000; Transfer(owner, addresses[i], 200000000000000000000); } } // To Distribute AirDrops of Remaining Token To Bounty (Press Release Post, Article submission, Blog submission, Social Sharing Etc) function AirDropPayBitsBounty(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 100000000000000000000; balances[addresses[i]] += 100000000000000000000; Transfer(owner, addresses[i], 100000000000000000000); } } // Total Supply of Coin will be 21 Million only function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } // For Future Development 20% of token will be used function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
To Distribute AirDrops for Applicants of Round 1
function AirDropPayBitsR1(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 400000000000000000000; balances[addresses[i]] += 400000000000000000000; Transfer(owner, addresses[i], 400000000000000000000); } }
12,572,186
pragma solidity ^0.5.0; import "../Processor.sol"; contract TestProcessor is Processor { event LogItemCreated(bytes32 _id); function() external payable {} //Wrapper function to test internal method function callCreate( address payable _sender, bytes memory _recipient, address _token, uint256 _amount ) public returns(bytes32) { bytes32 id = create(_sender, _recipient, _token, _amount); emit LogItemCreated(id); return id; } //Wrapper function to test internal method function callComplete( bytes32 _id ) public { complete(_id); } //Wrapper function to test internal method function callIsLocked( bytes32 _id ) public view returns(bool) { return isLocked(_id); } //Wrapper function to test internal method function callGetItem( bytes32 _id ) public view returns(address, bytes memory, address, uint256, uint256) { return getItem(_id); } }
Wrapper function to test internal method
function callIsLocked( bytes32 _id ) public view returns(bool) { return isLocked(_id); }
15,782,601
pragma solidity ^0.8.0; // Copyright 2020 Keyko GmbH. // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol'; /** * @title DID Registry Library * @author Keyko * * @dev All function calls are currently implemented without side effects */ library DIDRegistryLibrary { using SafeMathUpgradeable for uint256; // DIDRegistry Entity struct DIDRegister { // DIDRegistry entry owner address owner; // The percent of the sale that is going back to the original `creator` in the secondary market uint8 royalties; // Flag to control if NFTs config was already initialized bool nftInitialized; // Flag to control if NFTs config was already initialized (erc 721) bool nft721Initialized; // DIDRegistry original creator, this can't be modified after the asset is registered address creator; // Checksum associated to the DID bytes32 lastChecksum; // URL to the metadata associated to the DID string url; // Who was the last one updated the entry address lastUpdatedBy; // When was the last time was updated uint256 blockNumberUpdated; // Providers able to manage this entry address[] providers; // Delegates able to register provenance events on behalf of the owner or providers address[] delegates; // The NFTs supply associated to the DID uint256 nftSupply; // The max number of NFTs associated to the DID that can be minted uint256 mintCap; } // List of DID's registered in the system struct DIDRegisterList { mapping(bytes32 => DIDRegister) didRegisters; bytes32[] didRegisterIds; } /** * @notice update the DID store * @dev access modifiers and storage pointer should be implemented in DIDRegistry * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _checksum includes a one-way HASH calculated using the DDO content * @param _url includes the url resolving to the DID Document (DDO) */ function update( DIDRegisterList storage _self, bytes32 _did, bytes32 _checksum, string calldata _url ) external returns (uint size) { address didOwner = _self.didRegisters[_did].owner; address creator = _self.didRegisters[_did].creator; if (didOwner == address(0)) { didOwner = msg.sender; _self.didRegisterIds.push(_did); creator = didOwner; } _self.didRegisters[_did] = DIDRegister({ owner: didOwner, creator: creator, lastChecksum: _checksum, url: _url, lastUpdatedBy: msg.sender, blockNumberUpdated: block.number, providers: new address[](0), delegates: new address[](0), nftSupply: 0, mintCap: 0, royalties: 0, nftInitialized: false, nft721Initialized: false }); return _self.didRegisterIds.length; } /** * @notice initializeNftConfig creates the initial setup of NFTs minting and royalties distribution. * After this initial setup, this data can't be changed anymore for the DID given, even for the owner of the DID. * The reason of this is to avoid minting additional NFTs after the initial agreement, what could affect the * valuation of NFTs of a DID already created. * @dev update the DID registry providers list by adding the mintCap and royalties configuration * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _cap refers to the mint cap * @param _royalties refers to the royalties to reward to the DID creator in the secondary market * The royalties in secondary market for the creator should be between 0% >= x < 100% */ function initializeNftConfig( DIDRegisterList storage _self, bytes32 _did, uint256 _cap, uint8 _royalties ) internal { require(_self.didRegisters[_did].owner != address(0), 'DID not stored'); require(!_self.didRegisters[_did].nftInitialized, 'NFT already initialized'); require(_royalties < 100, 'Invalid royalties number'); require(_royalties >= _self.didRegisters[_did].royalties, 'Cannot decrease royalties'); _self.didRegisters[_did].mintCap = _cap; _self.didRegisters[_did].royalties = _royalties; _self.didRegisters[_did].nftInitialized = true; } function initializeNft721Config( DIDRegisterList storage _self, bytes32 _did, uint8 _royalties ) internal { require(_self.didRegisters[_did].owner != address(0), 'DID not stored'); require(!_self.didRegisters[_did].nft721Initialized, 'NFT already initialized'); require(_royalties < 100, 'Invalid royalties number'); require(_royalties >= _self.didRegisters[_did].royalties, 'Cannot decrease royalties'); _self.didRegisters[_did].royalties = _royalties; _self.didRegisters[_did].nft721Initialized = true; } /** * @notice areRoyaltiesValid checks if for a given DID and rewards distribution, this allocate the * original creator royalties properly * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _amounts refers to the amounts to reward * @param _receivers refers to the receivers of rewards * @return true if the rewards distribution respect the original creator royalties */ function areRoyaltiesValid( DIDRegisterList storage _self, bytes32 _did, uint256[] memory _amounts, address[] memory _receivers ) internal view returns (bool) { // If (did.creator == did.owner) - It means the DID is still a first sale so no royalties needed // returns true; if (_self.didRegisters[_did].owner == _self.didRegisters[_did].creator) { return true; } // If there are no royalties everything is good if (_self.didRegisters[_did].royalties == 0) { return true; } // If (sum(_amounts) == 0) - It means there is no payment so everything is valid // returns true; uint256 _totalAmount = 0; for(uint i = 0; i < _amounts.length; i++) _totalAmount = _totalAmount.add(_amounts[i]); if (_totalAmount == 0) return true; // If (_did.creator is not in _receivers) - It means the original creator is not included as part of the payment // return false; bool found = false; uint256 index; for (index = 0; index < _receivers.length; index++) { if (_self.didRegisters[_did].creator == _receivers[index]) { found = true; break; } } if (!found) // The creator royalties are not part of the rewards return false; // If the amount to receive by the creator is lower than royalties the calculation is not valid // return false; uint256 _requiredRoyalties = ((_totalAmount.mul(_self.didRegisters[_did].royalties)) / 100); // Check if royalties are enough // Are we paying enough royalties in the secondary market to the original creator? return (_amounts[index] >= _requiredRoyalties); } /** * @notice addProvider add provider to DID registry * @dev update the DID registry providers list by adding a new provider * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param provider the provider's address */ function addProvider( DIDRegisterList storage _self, bytes32 _did, address provider ) internal { require( provider != address(0) && provider != address(this), 'Invalid provider' ); if (!isProvider(_self, _did, provider)) { _self.didRegisters[_did].providers.push(provider); } } /** * @notice removeProvider remove provider from DID registry * @dev update the DID registry providers list by removing an existing provider * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _provider the provider's address */ function removeProvider( DIDRegisterList storage _self, bytes32 _did, address _provider ) internal returns(bool) { require( _provider != address(0), 'Invalid provider' ); int256 i = getProviderIndex(_self, _did, _provider); if (i == -1) { return false; } delete _self.didRegisters[_did].providers[uint256(i)]; return true; } /** * @notice updateDIDOwner transfer DID ownership to a new owner * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _newOwner the new DID owner address */ function updateDIDOwner( DIDRegisterList storage _self, bytes32 _did, address _newOwner ) internal { require(_newOwner != address(0)); _self.didRegisters[_did].owner = _newOwner; } /** * @notice isProvider check whether DID provider exists * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _provider the provider's address * @return true if the provider already exists */ function isProvider( DIDRegisterList storage _self, bytes32 _did, address _provider ) public view returns(bool) { if (getProviderIndex(_self, _did, _provider) == -1) return false; return true; } /** * @notice getProviderIndex get the index of a provider * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param provider the provider's address * @return the index if the provider exists otherwise return -1 */ function getProviderIndex( DIDRegisterList storage _self, bytes32 _did, address provider ) private view returns(int256 ) { for (uint256 i = 0; i < _self.didRegisters[_did].providers.length; i++) { if (provider == _self.didRegisters[_did].providers[i]) { return int(i); } } return - 1; } //////////// DELEGATE METHODS /** * @notice addDelegate add delegate to DID registry * @dev update the DID registry delegates list by adding a new delegate * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param delegate the delegate's address */ function addDelegate( DIDRegisterList storage _self, bytes32 _did, address delegate ) internal { require(delegate != address(0) && delegate != address(this)); if (!isDelegate(_self, _did, delegate)) { _self.didRegisters[_did].delegates.push(delegate); } } /** * @notice removeDelegate remove delegate from DID registry * @dev update the DID registry delegates list by removing an existing delegate * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _delegate the delegate's address */ function removeDelegate( DIDRegisterList storage _self, bytes32 _did, address _delegate ) internal returns(bool) { require(_delegate != address(0)); int256 i = getDelegateIndex(_self, _did, _delegate); if (i == -1) { return false; } delete _self.didRegisters[_did].delegates[uint256(i)]; return true; } /** * @notice isDelegate check whether DID delegate exists * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _delegate the delegate's address * @return true if the delegate already exists */ function isDelegate( DIDRegisterList storage _self, bytes32 _did, address _delegate ) public view returns(bool) { if (getDelegateIndex(_self, _did, _delegate) == -1) return false; return true; } /** * @notice getDelegateIndex get the index of a delegate * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param delegate the delegate's address * @return the index if the delegate exists otherwise return -1 */ function getDelegateIndex( DIDRegisterList storage _self, bytes32 _did, address delegate ) private view returns(int256) { for (uint256 i = 0; i < _self.didRegisters[_did].delegates.length; i++) { if (delegate == _self.didRegisters[_did].delegates[i]) { return int(i); } } return - 1; } }
initializeNftConfig creates the initial setup of NFTs minting and royalties distribution. After this initial setup, this data can't be changed anymore for the DID given, even for the owner of the DID. The reason of this is to avoid minting additional NFTs after the initial agreement, what could affect the valuation of NFTs of a DID already created. update the DID registry providers list by adding the mintCap and royalties configuration _self refers to storage pointer _did refers to decentralized identifier (a byte32 length ID) _cap refers to the mint cap _royalties refers to the royalties to reward to the DID creator in the secondary market The royalties in secondary market for the creator should be between 0% >= x < 100%/
function initializeNftConfig( DIDRegisterList storage _self, bytes32 _did, uint256 _cap, uint8 _royalties ) internal { require(_self.didRegisters[_did].owner != address(0), 'DID not stored'); require(!_self.didRegisters[_did].nftInitialized, 'NFT already initialized'); require(_royalties < 100, 'Invalid royalties number'); require(_royalties >= _self.didRegisters[_did].royalties, 'Cannot decrease royalties'); _self.didRegisters[_did].mintCap = _cap; _self.didRegisters[_did].royalties = _royalties; _self.didRegisters[_did].nftInitialized = true; }
12,991,466
pragma solidity ^0.4.23; /** * @title EvtAttendance * @author Vincent Serpoul * @dev contract for managing attendance today */ contract EvtAttendance { Evt[] evts; struct Evt { uint256 id; address organizer; string title; address[] attendees; mapping(address => bool) hasAttended; } event EvtCreated(address _organizer, uint256 _id, string _title); event EvtAttended(address _who, uint256 _id); /** * @dev allows attendees to attend * @param _title string title of the event */ function createEvt(string _title) public returns(uint256) { Evt memory evt; evt.id = evts.length; evt.organizer = msg.sender; evt.title = _title; evts.push(evt); emit EvtCreated(msg.sender, evt.id, _title); return evt.id; } /** * @dev allows attendees to attend * @param _evtId uint256 event id */ function attend(uint256 _evtId) public { evts[_evtId].attendees.push(msg.sender); evts[_evtId].hasAttended[msg.sender] = true; emit EvtAttended(msg.sender, _evtId); } /** * @dev know if a user has attended * @param _evtId uint256 event id */ function hasAttended(uint256 _evtId) view public returns(bool) { return evts[_evtId].hasAttended[msg.sender]; } /** * @dev get an event * @param _evtId uint256 event id */ function getEvent(uint256 _evtId) view public returns(uint256, address, string, address[]) { return (evts[_evtId].id, evts[_evtId].organizer, evts[_evtId].title, evts[_evtId].attendees); } /** * @dev get how many events have been created */ function getEventCount() view public returns(uint256) { return evts.length; } }
know if a user has attended _evtId uint256 event id/
function hasAttended(uint256 _evtId) view public returns(bool) { return evts[_evtId].hasAttended[msg.sender]; }
1,041,526
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.0; 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); } } 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; } } 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } 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"); } } } 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; } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.synthetix.io/contracts/Pausable abstract contract Pausable is Owned { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } // https://docs.synthetix.io/contracts/RewardsDistributionRecipient abstract contract RewardsDistributionRecipient is Owned { address public rewardsDistribution; function notifyRewardAmount(uint256 reward) external virtual; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract"); _; } function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount, bool payingCharges) external; function getReward() external; function exit() external; } contract LiquidityProvision is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public X22Token; IERC20 public stakingToken; address public wallet; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 30 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public coolDownPeriod = 691200; uint256 public withdrawCharges = 7; uint256 public minimumWithdraw = 0; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public requestedTime; mapping(address => uint256) public requestedAmount; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsDistribution, address _wallet, address _X22Token, address _stakingToken ) public Owned(_owner) { X22Token = IERC20(_X22Token); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; wallet = _wallet; } //Update the wallet function updateWallet(address _wallet) public onlyOwner { wallet = _wallet; } //Update withdraw charges function updateCharges(uint256 percentage) public onlyOwner { withdrawCharges = percentage; } //Update Cooldown period function updateCoolDownPeriod(uint256 NewPeriod) public onlyOwner { coolDownPeriod = NewPeriod.mul(86400); } /* ========== VIEWS ========== */ function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view override returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() external view override returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external override nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount, bool payingCharges) public override nonReentrant updateReward(msg.sender) { require(amount > minimumWithdraw, "Cannot withdraw 0"); if(payingCharges == true){ _balances[msg.sender] = _balances[msg.sender].sub(amount); _totalSupply = _totalSupply.sub(amount); uint256 fee = amount.mul(withdrawCharges).div(100); stakingToken.safeTransfer(wallet, fee); amount = amount.sub(fee); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } else{ if(requestedAmount[msg.sender] != amount){ requestedAmount[msg.sender] = amount; requestedTime[msg.sender] = block.timestamp; } } } function claim(bool payingCharges) public nonReentrant updateReward(msg.sender) { uint256 amount = requestedAmount[msg.sender]; if(payingCharges == true){ _balances[msg.sender] = _balances[msg.sender].sub(amount); _totalSupply = _totalSupply.sub(amount); uint256 fee = amount.mul(withdrawCharges).div(100); stakingToken.safeTransfer(wallet, fee); amount = amount.sub(fee); } else{ require(requestedTime[msg.sender].add(coolDownPeriod) <= block.timestamp, 'You can withdraw after 8 days of requesting otherwise pay charges first'); _balances[msg.sender] = _balances[msg.sender].sub(amount); _totalSupply = _totalSupply.sub(amount); } stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); requestedTime[msg.sender] = 0; requestedAmount[msg.sender] = 0; } function cancelWithdraw() public { requestedAmount[msg.sender] = 0; requestedTime[msg.sender] = 0; } function getReward() public override nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; X22Token.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external override { withdraw(_balances[msg.sender], true); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = X22Token.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require( tokenAddress != address(stakingToken) &&tokenAddress != address(X22Token), "Cannot withdraw the staking or rewards tokens" ); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( periodFinish == 0 || block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); }
Added to support recovering LP Rewards from other systems to be distributed to holders Cannot recover the staking token or the rewards token
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { require( tokenAddress != address(stakingToken) &&tokenAddress != address(X22Token), "Cannot withdraw the staking or rewards tokens" ); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); }
13,978,263
// SPDX-License-Identifier: MIT pragma solidity >= 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /** This is the MoneyPot contract. It will be used to distribute shares rewards to ELCTs stakers. This is owned by the team, and the team will be able to set start and end blocks to distribute daily or weekly rewards to ELCTs stakers. Owner --> TBD, it should be activated daily, do we need a timelock? Modified from Pancake SmartChef contract (https://bscscan.com/address/0xABFd8d1942628124aB971937154f826Bce86DcbC#code) */ contract MoneyPot is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 stakeToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward distribution occurs. uint256 accRewardPerShare; // Accumulated reward per share, times 1e12. See below. } // Token to stake IERC20 public stakingToken; // Token used as reward IERC20 public rewardToken; // Reward token given per block uint256 public rewardPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (address => UserInfo) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 private totalAllocPoint = 0; // The block number when reward mining starts. uint256 public startBlock; // The block number when reward mining ends. uint256 public bonusEndBlock; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event StopReward(uint256 blockNumber); constructor( IERC20 _stakingToken, IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { stakingToken = _stakingToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; // staking pool poolInfo.push(PoolInfo({ stakeToken: _stakingToken, allocPoint: 1000, // Max allocation to this single pool lastRewardBlock: startBlock, accRewardPerShare: 0 })); totalAllocPoint = 1000; } // Can be used for emergency to instantly stop rewards function stopReward() public onlyOwner { bonusEndBlock = block.number; emit StopReward(block.number); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from); } else if (_from >= bonusEndBlock) { return 0; } else { return bonusEndBlock.sub(_from); } } // View function to see pending Reward on frontend. function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 stokenSupply = pool.stakeToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && stokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(stokenSupply)); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 stokenSupply = pool.stakeToken.balanceOf(address(this)); if (stokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accRewardPerShare = pool.accRewardPerShare.add(tokenReward.mul(1e12).div(stokenSupply)); pool.lastRewardBlock = block.number; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Stake staking tokens to moneypot function deposit(uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } } if(_amount > 0) { pool.stakeToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Deposit(msg.sender, _amount); } /** Sets the startBlock and bonusEndBlock for the moneypot, making it easy to update the blocks distribute new rewards later in time. Resets also the lastRewardBlock. */ function setBlocksBoundaries(uint256 _startBlock, uint256 _endBlock) public onlyOwner { PoolInfo storage pool = poolInfo[0]; require(pool.lastRewardBlock <= _startBlock, "set: startBlock should be >= to the previous one"); require(bonusEndBlock <= _endBlock, "set: endBlock should be >= to the previous one"); require(_startBlock <= _endBlock, "set: _startBlock should be >= to endBlock"); updatePool(0); pool.lastRewardBlock = _startBlock; startBlock = _startBlock; bonusEndBlock = _endBlock; } // Withdraw stake tokens from STAKING. function withdraw(uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.stakeToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); emit Withdraw(msg.sender, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public nonReentrant { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; pool.stakeToken.safeTransfer(address(msg.sender), user.amount); user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, user.amount); } // Withdraw reward. EMERGENCY ONLY. function emergencyRewardWithdraw(uint256 _amount) public onlyOwner { require(_amount < rewardToken.balanceOf(address(this)), 'not enough token'); rewardToken.safeTransfer(address(msg.sender), _amount); } }
View function to see pending Reward on frontend.
function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 stokenSupply = pool.stakeToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && stokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(stokenSupply)); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); }
1,784,786
// SPDX-License-Identifier: GPL-3.0-or-later // Sources flattened with hardhat v2.6.1 https://hardhat.org // File interfaces/actions/IAction.sol pragma solidity 0.8.9; interface IAction { /** * @return the total amount of ETH (in wei) required to cover gas */ function getEthRequiredForGas(address payer) external view returns (uint256); function addUsableToken(address token) external returns (bool); function getUsableTokens() external view returns (address[] memory); function isUsable(address token) external view returns (bool); function getActionFee() external view returns (uint256); function getFeeHandler() external view returns (address); function executeActionFee() external returns (uint256); function executeSwapperSlippage() external returns (uint256); function executeFeeHandler() external returns (address); } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); /** * @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 interfaces/IPreparable.sol pragma solidity 0.8.9; interface IPreparable { event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay); event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay); event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue); event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue); event ConfigReset(bytes32 indexed key); } // File interfaces/IStrategy.sol pragma solidity 0.8.9; interface IStrategy { function name() external view returns (string memory); function deposit() external payable returns (bool); function balance() external view returns (uint256); function withdraw(uint256 amount) external returns (bool); function withdrawAll() external returns (uint256); function harvestable() external view returns (uint256); function harvest() external returns (uint256); function strategist() external view returns (address); function shutdown() external returns (bool); function hasPendingFunds() external view returns (bool); } // File interfaces/IVault.sol pragma solidity 0.8.9; /** * @title Interface for a Vault */ interface IVault is IPreparable { event StrategyActivated(address indexed strategy); event StrategyDeactivated(address indexed strategy); /** * @dev 'netProfit' is the profit after all fees have been deducted */ event Harvest(uint256 indexed netProfit, uint256 indexed loss); function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external; function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256); function deposit() external payable; function withdraw(uint256 amount) external returns (bool); function initializeStrategy(address strategy_) external returns (bool); function withdrawAll() external; function withdrawFromReserve(uint256 amount) external; function getStrategy() external view returns (IStrategy); function getStrategiesWaitingForRemoval() external view returns (address[] memory); function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256); function getTotalUnderlying() external view returns (uint256); function getUnderlying() external view returns (address); } // File interfaces/pool/ILiquidityPool.sol pragma solidity 0.8.9; interface ILiquidityPool is IPreparable { event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens); event DepositFor( address indexed minter, address indexed mintee, uint256 depositAmount, uint256 mintedLpTokens ); event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens); event LpTokenSet(address indexed lpToken); event StakerVaultSet(address indexed stakerVault); function redeem(uint256 redeemTokens) external returns (uint256); function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256); function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256); function deposit(uint256 mintAmount) external payable returns (uint256); function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256); function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable returns (uint256); function depositFor(address account, uint256 depositAmount) external payable returns (uint256); function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) external payable returns (uint256); function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external returns (uint256); function handleLpTokenTransfer( address from, address to, uint256 amount ) external; function executeNewVault() external returns (address); function executeNewMaxWithdrawalFee() external returns (uint256); function executeNewRequiredReserves() external returns (uint256); function executeNewReserveDeviation() external returns (uint256); function setLpToken(address _lpToken) external returns (bool); function setStaker() external returns (bool); function isCapped() external returns (bool); function uncap() external returns (bool); function updateDepositCap(uint256 _depositCap) external returns (bool); function getUnderlying() external view returns (address); function getLpToken() external view returns (address); function getWithdrawalFee(address account, uint256 amount) external view returns (uint256); function getVault() external view returns (IVault); function exchangeRate() external view returns (uint256); } // File interfaces/IGasBank.sol pragma solidity 0.8.9; interface IGasBank { event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, address indexed receiver, uint256 value); function depositFor(address account) external payable; function withdrawUnused(address account) external; function withdrawFrom(address account, uint256 amount) external; function withdrawFrom( address account, address payable to, uint256 amount ) external; function balanceOf(address account) external view returns (uint256); } // File interfaces/oracles/IOracleProvider.sol pragma solidity 0.8.9; interface IOracleProvider { /// @notice Quotes the USD price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the USD price of the asset function getPriceUSD(address baseAsset) external view returns (uint256); /// @notice Quotes the ETH price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the ETH price of the asset function getPriceETH(address baseAsset) external view returns (uint256); } // File libraries/AddressProviderMeta.sol pragma solidity 0.8.9; library AddressProviderMeta { struct Meta { bool freezable; bool frozen; } function fromUInt(uint256 value) internal pure returns (Meta memory) { Meta memory meta; meta.freezable = (value & 1) == 1; meta.frozen = ((value >> 1) & 1) == 1; return meta; } function toUInt(Meta memory meta) internal pure returns (uint256) { uint256 value; value |= meta.freezable ? 1 : 0; value |= meta.frozen ? 1 << 1 : 0; return value; } } // File interfaces/IAddressProvider.sol pragma solidity 0.8.9; // solhint-disable ordering interface IAddressProvider is IPreparable { event KnownAddressKeyAdded(bytes32 indexed key); event StakerVaultListed(address indexed stakerVault); event StakerVaultDelisted(address indexed stakerVault); event ActionListed(address indexed action); event PoolListed(address indexed pool); event PoolDelisted(address indexed pool); event VaultUpdated(address indexed previousVault, address indexed newVault); /** Key functions */ function getKnownAddressKeys() external view returns (bytes32[] memory); function freezeAddress(bytes32 key) external; /** Pool functions */ function allPools() external view returns (address[] memory); function addPool(address pool) external; function poolsCount() external view returns (uint256); function getPoolAtIndex(uint256 index) external view returns (address); function isPool(address pool) external view returns (bool); function removePool(address pool) external returns (bool); function getPoolForToken(address token) external view returns (ILiquidityPool); function safeGetPoolForToken(address token) external view returns (address); /** Vault functions */ function updateVault(address previousVault, address newVault) external; function allVaults() external view returns (address[] memory); function vaultsCount() external view returns (uint256); function getVaultAtIndex(uint256 index) external view returns (address); function isVault(address vault) external view returns (bool); /** Action functions */ function allActions() external view returns (address[] memory); function addAction(address action) external returns (bool); function isAction(address action) external view returns (bool); /** Address functions */ function initializeAddress( bytes32 key, address initialAddress, bool frezable ) external; function initializeAndFreezeAddress(bytes32 key, address initialAddress) external; function getAddress(bytes32 key) external view returns (address); function getAddress(bytes32 key, bool checkExists) external view returns (address); function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory); function prepareAddress(bytes32 key, address newAddress) external returns (bool); function executeAddress(bytes32 key) external returns (address); function resetAddress(bytes32 key) external returns (bool); /** Staker vault functions */ function allStakerVaults() external view returns (address[] memory); function tryGetStakerVault(address token) external view returns (bool, address); function getStakerVault(address token) external view returns (address); function addStakerVault(address stakerVault) external returns (bool); function isStakerVault(address stakerVault, address token) external view returns (bool); function isStakerVaultRegistered(address stakerVault) external view returns (bool); function isWhiteListedFeeHandler(address feeHandler) external view returns (bool); } // File interfaces/tokenomics/IInflationManager.sol pragma solidity 0.8.9; interface IInflationManager { event KeeperGaugeListed(address indexed pool, address indexed keeperGauge); event AmmGaugeListed(address indexed token, address indexed ammGauge); event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge); event AmmGaugeDelisted(address indexed token, address indexed ammGauge); /** Pool functions */ function setKeeperGauge(address pool, address _keeperGauge) external returns (bool); function setAmmGauge(address token, address _ammGauge) external returns (bool); function getAllAmmGauges() external view returns (address[] memory); function getLpRateForStakerVault(address stakerVault) external view returns (uint256); function getKeeperRateForPool(address pool) external view returns (uint256); function getAmmRateForToken(address token) external view returns (uint256); function getKeeperWeightForPool(address pool) external view returns (uint256); function getAmmWeightForToken(address pool) external view returns (uint256); function getLpPoolWeight(address pool) external view returns (uint256); function getKeeperGaugeForPool(address pool) external view returns (address); function getAmmGaugeForToken(address token) external view returns (address); function isInflationWeightManager(address account) external view returns (bool); function removeStakerVaultFromInflation(address stakerVault, address lpToken) external; function addGaugeForVault(address lpToken) external returns (bool); function whitelistGauge(address gauge) external; function checkpointAllGauges() external returns (bool); function mintRewards(address beneficiary, uint256 amount) external; function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool) external returns (bool); /** Weight setter functions **/ function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool); function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool); function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool); function executeLpPoolWeight(address lpToken) external returns (uint256); function executeAmmTokenWeight(address token) external returns (uint256); function executeKeeperPoolWeight(address pool) external returns (uint256); function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights) external returns (bool); function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights) external returns (bool); function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights) external returns (bool); function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool); function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool); function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool); } // File interfaces/IController.sol pragma solidity 0.8.9; // solhint-disable ordering interface IController is IPreparable { function addressProvider() external view returns (IAddressProvider); function inflationManager() external view returns (IInflationManager); function addStakerVault(address stakerVault) external returns (bool); function removePool(address pool) external returns (bool); /** Keeper functions */ function prepareKeeperRequiredStakedBKD(uint256 amount) external; function executeKeeperRequiredStakedBKD() external; function getKeeperRequiredStakedBKD() external view returns (uint256); function canKeeperExecuteAction(address keeper) external view returns (bool); /** Miscellaneous functions */ function getTotalEthRequiredForGas(address payer) external view returns (uint256); } // File interfaces/IStakerVault.sol pragma solidity 0.8.9; interface IStakerVault { event Staked(address indexed account, uint256 amount); event Unstaked(address indexed account, uint256 amount); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function initialize(address _token) external; function initializeLpGauge(address _lpGauge) external returns (bool); function stake(uint256 amount) external returns (bool); function stakeFor(address account, uint256 amount) external returns (bool); function unstake(uint256 amount) external returns (bool); function unstakeFor( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transfer(address account, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function getToken() external view returns (address); function balanceOf(address account) external view returns (uint256); function stakedAndActionLockedBalanceOf(address account) external view returns (uint256); function actionLockedBalanceOf(address account) external view returns (uint256); function increaseActionLockedBalance(address account, uint256 amount) external returns (bool); function decreaseActionLockedBalance(address account, uint256 amount) external returns (bool); function getStakedByActions() external view returns (uint256); function addStrategy(address strategy) external returns (bool); function getPoolTotalStaked() external view returns (uint256); function prepareLpGauge(address _lpGauge) external returns (bool); function executeLpGauge() external returns (bool); function getLpGauge() external view returns (address); function poolCheckpoint() external returns (bool); function isStrategy(address user) external view returns (bool); } // File interfaces/IVaultReserve.sol pragma solidity 0.8.9; interface IVaultReserve { event Deposit(address indexed vault, address indexed token, uint256 amount); event Withdraw(address indexed vault, address indexed token, uint256 amount); event VaultListed(address indexed vault); function deposit(address token, uint256 amount) external payable returns (bool); function withdraw(address token, uint256 amount) external returns (bool); function getBalance(address vault, address token) external view returns (uint256); function canWithdraw(address vault) external view returns (bool); } // File interfaces/IRoleManager.sol pragma solidity 0.8.9; interface IRoleManager { event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, address account ) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, bytes32 role3, address account ) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } // File interfaces/tokenomics/IBkdToken.sol pragma solidity 0.8.9; interface IBkdToken is IERC20 { function mint(address account, uint256 amount) external; } // File libraries/AddressProviderKeys.sol pragma solidity 0.8.9; library AddressProviderKeys { bytes32 internal constant _TREASURY_KEY = "treasury"; bytes32 internal constant _GAS_BANK_KEY = "gasBank"; bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve"; bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry"; bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider"; bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory"; bytes32 internal constant _CONTROLLER_KEY = "controller"; bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker"; bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager"; } // File libraries/AddressProviderHelpers.sol pragma solidity 0.8.9; library AddressProviderHelpers { /** * @return The address of the treasury. */ function getTreasury(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._TREASURY_KEY); } /** * @return The gas bank. */ function getGasBank(IAddressProvider provider) internal view returns (IGasBank) { return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY)); } /** * @return The address of the vault reserve. */ function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) { return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY)); } /** * @return The address of the swapperRegistry. */ function getSwapperRegistry(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY); } /** * @return The oracleProvider. */ function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) { return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY)); } /** * @return the address of the BKD locker */ function getBKDLocker(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY); } /** * @return the address of the BKD locker */ function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); } /** * @return the controller */ function getController(IAddressProvider provider) internal view returns (IController) { return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY)); } } // File libraries/Errors.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Error { string internal constant ADDRESS_WHITELISTED = "address already whitelisted"; string internal constant ADMIN_ALREADY_SET = "admin has already been set once"; string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted"; string internal constant ADDRESS_NOT_FOUND = "address not found"; string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once"; string internal constant CONTRACT_PAUSED = "contract is paused"; string internal constant INVALID_AMOUNT = "invalid amount"; string internal constant INVALID_INDEX = "invalid index"; string internal constant INVALID_VALUE = "invalid msg.value"; string internal constant INVALID_SENDER = "invalid msg.sender"; string internal constant INVALID_TOKEN = "token address does not match pool's LP token address"; string internal constant INVALID_DECIMALS = "incorrect number of decimals"; string internal constant INVALID_ARGUMENT = "invalid argument"; string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted"; string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_POOL_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_LP_TOKEN_IMPLEMENTATION = "invalid LP Token implementation for given coin"; string internal constant INVALID_VAULT_IMPLEMENTATION = "invalid vault implementation for given coin"; string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION = "invalid stakerVault implementation for given coin"; string internal constant INSUFFICIENT_BALANCE = "insufficient balance"; string internal constant ADDRESS_ALREADY_SET = "Address is already set"; string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance"; string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received"; string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist"; string internal constant ADDRESS_FROZEN = "address is frozen"; string internal constant ROLE_EXISTS = "role already exists"; string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role"; string internal constant UNAUTHORIZED_ACCESS = "unauthorized access"; string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed"; string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed"; string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed"; string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed"; string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10"; string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold"; string internal constant NO_POSITION_EXISTS = "no position exists"; string internal constant POSITION_ALREADY_EXISTS = "position already exists"; string internal constant PROTOCOL_NOT_FOUND = "protocol not found"; string internal constant TOP_UP_FAILED = "top up failed"; string internal constant SWAP_PATH_NOT_FOUND = "swap path not found"; string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported"; string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN = "not enough funds were withdrawn from the pool"; string internal constant FAILED_TRANSFER = "transfer failed"; string internal constant FAILED_MINT = "mint failed"; string internal constant FAILED_REPAY_BORROW = "repay borrow failed"; string internal constant FAILED_METHOD_CALL = "method call failed"; string internal constant NOTHING_TO_CLAIM = "there is no claimable balance"; string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance"; string internal constant INVALID_MINTER = "the minter address of the LP token and the pool address do not match"; string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token"; string internal constant DEADLINE_NOT_ZERO = "deadline must be 0"; string internal constant DEADLINE_NOT_SET = "deadline is 0"; string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet"; string internal constant DELAY_TOO_SHORT = "delay be at least 3 days"; string internal constant INSUFFICIENT_UPDATE_BALANCE = "insufficient funds for updating the position"; string internal constant SAME_AS_CURRENT = "value must be different to existing value"; string internal constant NOT_CAPPED = "the pool is not currently capped"; string internal constant ALREADY_CAPPED = "the pool is already capped"; string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap"; string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas"; string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw"; string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas"; string internal constant DEPOSIT_FAILED = "deposit failed"; string internal constant GAS_TOO_HIGH = "too much ETH used for gas"; string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas"; string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add"; string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed"; string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet"; string internal constant UNDERLYING_NOT_WITHDRAWABLE = "pool does not support additional underlying coins to be withdrawn"; string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down"; string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist"; string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported"; string internal constant NO_DEX_SET = "no dex has been set for token"; string internal constant INVALID_TOKEN_PAIR = "invalid token pair"; string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action"; string internal constant ADDRESS_NOT_ACTION = "address is not registered action"; string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance"; string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve"; string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block"; string internal constant GAUGE_EXISTS = "Gauge already exists"; string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist"; string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex"; string internal constant PREPARED_WITHDRAWAL = "Cannot relock funds when withdrawal is being prepared"; string internal constant ASSET_NOT_SUPPORTED = "Asset not supported"; string internal constant STALE_PRICE = "Price is stale"; string internal constant NEGATIVE_PRICE = "Price is negative"; string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked"; string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded"; } // File contracts/utils/Preparable.sol pragma solidity 0.8.9; /** * @notice Implements the base logic for a two-phase commit * @dev This does not implements any access-control so publicly exposed * callers should make sure to have the proper checks in palce */ contract Preparable is IPreparable { uint256 private constant _MIN_DELAY = 3 days; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingUInts256; mapping(bytes32 => address) public currentAddresses; mapping(bytes32 => uint256) public currentUInts256; /** * @dev Deadlines shares the same namespace regardless of the type * of the pending variable so this needs to be enforced in the caller */ mapping(bytes32 => uint256) public deadlines; function _prepareDeadline(bytes32 key, uint256 delay) internal { require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO); require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT); deadlines[key] = block.timestamp + delay; } /** * @notice Prepares an uint256 that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, uint256 value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingUInts256[key] = value; emit ConfigPreparedNumber(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay */ function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Prepares an address that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, address value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingAddresses[key] = value; emit ConfigPreparedAddress(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay */ function _prepare(bytes32 key, address value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Reset a uint256 key * @return `true` if success. */ function _resetUInt256Config(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingUInts256[key] = 0; emit ConfigReset(key); return true; } /** * @notice Reset an address key * @return `true` if success. */ function _resetAddressConfig(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingAddresses[key] = address(0); emit ConfigReset(key); return true; } /** * @dev Checks the deadline of the key and reset it */ function _executeDeadline(bytes32 key) internal { uint256 deadline = deadlines[key]; require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED); require(deadline != 0, Error.DEADLINE_NOT_SET); deadlines[key] = 0; } /** * @notice Execute uint256 config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeUInt256(bytes32 key) internal returns (uint256) { _executeDeadline(key); uint256 newValue = pendingUInts256[key]; _setConfig(key, newValue); return newValue; } /** * @notice Execute address config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeAddress(bytes32 key) internal returns (address) { _executeDeadline(key); address newValue = pendingAddresses[key]; _setConfig(key, newValue); return newValue; } function _setConfig(bytes32 key, address value) internal returns (address) { address oldValue = currentAddresses[key]; currentAddresses[key] = value; pendingAddresses[key] = address(0); deadlines[key] = 0; emit ConfigUpdatedAddress(key, oldValue, value); return value; } function _setConfig(bytes32 key, uint256 value) internal returns (uint256) { uint256 oldValue = currentUInts256[key]; currentUInts256[key] = value; pendingUInts256[key] = 0; deadlines[key] = 0; emit ConfigUpdatedNumber(key, oldValue, value); return value; } } // File libraries/Roles.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Roles { bytes32 internal constant GOVERNANCE = "governance"; bytes32 internal constant ADDRESS_PROVIDER = "address_provider"; bytes32 internal constant POOL_FACTORY = "pool_factory"; bytes32 internal constant CONTROLLER = "controller"; bytes32 internal constant GAUGE_ZAP = "gauge_zap"; bytes32 internal constant MAINTENANCE = "maintenance"; bytes32 internal constant INFLATION_MANAGER = "inflation_manager"; bytes32 internal constant POOL = "pool"; bytes32 internal constant VAULT = "vault"; } // File contracts/access/AuthorizationBase.sol pragma solidity 0.8.9; /** * @notice Provides modifiers for authorization */ abstract contract AuthorizationBase { /** * @notice Only allows a sender with `role` to perform the given action */ modifier onlyRole(bytes32 role) { require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with GOVERNANCE role to perform the given action */ modifier onlyGovernance() { require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles2(bytes32 role1, bytes32 role2) { require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles3( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _roleManager().hasAnyRole(role1, role2, role3, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } function roleManager() external view virtual returns (IRoleManager) { return _roleManager(); } function _roleManager() internal view virtual returns (IRoleManager); } // File contracts/access/Authorization.sol pragma solidity 0.8.9; contract Authorization is AuthorizationBase { IRoleManager internal immutable __roleManager; constructor(IRoleManager roleManager) { __roleManager = roleManager; } function _roleManager() internal view override returns (IRoleManager) { return __roleManager; } } // File contracts/Controller.sol pragma solidity 0.8.9; contract Controller is IController, Authorization, Preparable { using AddressProviderHelpers for IAddressProvider; IAddressProvider public immutable override addressProvider; IInflationManager public inflationManager; bytes32 internal constant _KEEPER_REQUIRED_STAKED_BKD = "KEEPER_REQUIRED_STAKED_BKD"; constructor(IAddressProvider _addressProvider) Authorization(_addressProvider.getRoleManager()) { addressProvider = _addressProvider; } function setInflationManager(address _inflationManager) external onlyGovernance { require(address(inflationManager) == address(0), Error.ADDRESS_ALREADY_SET); require(_inflationManager != address(0), Error.INVALID_ARGUMENT); inflationManager = IInflationManager(_inflationManager); } function addStakerVault(address stakerVault) external override onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY) returns (bool) { if (!addressProvider.addStakerVault(stakerVault)) { return false; } if (address(inflationManager) != address(0)) { address lpGauge = IStakerVault(stakerVault).getLpGauge(); if (lpGauge != address(0)) { inflationManager.whitelistGauge(lpGauge); } } return true; } /** * @notice Delists pool. * @param pool Address of pool to delist. * @return `true` if successful. */ function removePool(address pool) external override onlyGovernance returns (bool) { if (!addressProvider.removePool(pool)) { return false; } address lpToken = ILiquidityPool(pool).getLpToken(); if (address(inflationManager) != address(0)) { (bool exists, address stakerVault) = addressProvider.tryGetStakerVault(lpToken); if (exists) { inflationManager.removeStakerVaultFromInflation(stakerVault, lpToken); } } return true; } /** * @notice Prepares the minimum amount of staked BKD required by a keeper */ function prepareKeeperRequiredStakedBKD(uint256 amount) external override onlyGovernance { require(addressProvider.getBKDLocker() != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); _prepare(_KEEPER_REQUIRED_STAKED_BKD, amount); } /** * @notice Sets the minimum amount of staked BKD required by a keeper to the prepared value */ function executeKeeperRequiredStakedBKD() external override { _executeUInt256(_KEEPER_REQUIRED_STAKED_BKD); } /** * @notice Returns true if the given keeper has enough staked BKD to execute actions */ function canKeeperExecuteAction(address keeper) external view override returns (bool) { uint256 requiredBKD = getKeeperRequiredStakedBKD(); return requiredBKD == 0 || IERC20(addressProvider.getBKDLocker()).balanceOf(keeper) >= requiredBKD; } /** * @return Returns the minimum amount of staked BKD required by a keeper */ function getKeeperRequiredStakedBKD() public view override returns (uint256) { return currentUInts256[_KEEPER_REQUIRED_STAKED_BKD]; } /** * @return the total amount of ETH require by `payer` to cover the fees for * positions registered in all actions */ function getTotalEthRequiredForGas(address payer) external view override returns (uint256) { // solhint-disable-previous-line ordering uint256 totalEthRequired = 0; address[] memory actions = addressProvider.allActions(); uint256 numActions = actions.length; for (uint256 i = 0; i < numActions; i++) { totalEthRequired += IAction(actions[i]).getEthRequiredForGas(payer); } return totalEthRequired; } }
return the address of the BKD locker/
function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); }
1,472,089
./partial_match/3/0xFa795A11f1C5E29af5318BEA3205e60A4e9A92c5/sources/MyTok.sol
================= Crowdsale Only =================
function mint(address _to, uint _amount) public returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; }
5,276,369
./full_match/5/0xEF7707e8049d5D856fffF75A1C0CC4De9d1e3100/sources/project_/contracts/TCRVoting.sol
This function returns if a specific curator is voted for a registry or not. registryId is the registry id curator is the address of the curator return true or false./
function isCuratorVotedForRegistry(bytes32 registryId, address curator) public view returns (bool) { uint256 curatorAllVotes = curatorVotedRegistries[curator].length; bool isVoted = false; for (uint256 i = 0; i < curatorAllVotes; i++) { if (curatorVotedRegistries[curator][i] == registryId) { isVoted = true; } } return isVoted; }
1,902,340
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // ========== External imports ========== import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; // ========== Internal imports ========== import { IDropERC721 } from "../interfaces/drop/IDropERC721.sol"; import { ITWFee } from "../interfaces/ITWFee.sol"; import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol"; import "../lib/CurrencyTransferLib.sol"; import "../lib/FeeType.sol"; import "../lib/MerkleProof.sol"; contract DropERC721 is Initializable, ReentrancyGuardUpgradeable, ERC2771ContextUpgradeable, MulticallUpgradeable, AccessControlEnumerableUpgradeable, ERC721EnumerableUpgradeable, IDropERC721 { using BitMapsUpgradeable for BitMapsUpgradeable.BitMap; using StringsUpgradeable for uint256; /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ bytes32 private constant MODULE_TYPE = bytes32("DropERC721"); uint256 private constant VERSION = 2; /// @dev Only transfers to or from TRANSFER_ROLE holders are valid, when transfers are restricted. bytes32 private constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); /// @dev Only MINTER_ROLE holders can lazy mint NFTs. bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @dev Max bps in the thirdweb system. uint256 private constant MAX_BPS = 10_000; /// @dev The thirdweb contract with fee related information. ITWFee public immutable thirdwebFee; /// @dev Owner of the contract (purpose: OpenSea compatibility) address private _owner; /// @dev The next token ID of the NFT to "lazy mint". uint256 public nextTokenIdToMint; /// @dev The next token ID of the NFT that can be claimed. uint256 public nextTokenIdToClaim; /// @dev The address that receives all primary sales value. address public primarySaleRecipient; /// @dev The max number of NFTs a wallet can claim. uint256 public maxWalletClaimCount; /// @dev Global max total supply of NFTs. uint256 public maxTotalSupply; /// @dev The address that receives all platform fees from all sales. address private platformFeeRecipient; /// @dev The % of primary sales collected as platform fees. uint16 private platformFeeBps; /// @dev The (default) address that receives all royalty value. address private royaltyRecipient; /// @dev The (default) % of a sale to take as royalty (in basis points). uint16 private royaltyBps; /// @dev Contract level metadata. string public contractURI; /// @dev Largest tokenId of each batch of tokens with the same baseURI uint256[] public baseURIIndices; /// @dev The set of all claim conditions, at any given moment. ClaimConditionList public claimCondition; /*/////////////////////////////////////////////////////////////// Mappings //////////////////////////////////////////////////////////////*/ /** * @dev Mapping from 'Largest tokenId of a batch of tokens with the same baseURI' * to base URI for the respective batch of tokens. **/ mapping(uint256 => string) private baseURI; /** * @dev Mapping from 'Largest tokenId of a batch of 'delayed-reveal' tokens with * the same baseURI' to encrypted base URI for the respective batch of tokens. **/ mapping(uint256 => bytes) public encryptedBaseURI; /// @dev Mapping from address => total number of NFTs a wallet has claimed. mapping(address => uint256) public walletClaimCount; /// @dev Token ID => royalty recipient and bps for token mapping(uint256 => RoyaltyInfo) private royaltyInfoForToken; /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ constructor(address _thirdwebFee) initializer { thirdwebFee = ITWFee(_thirdwebFee); } /// @dev Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _name, string memory _symbol, string memory _contractURI, address[] memory _trustedForwarders, address _saleRecipient, address _royaltyRecipient, uint128 _royaltyBps, uint128 _platformFeeBps, address _platformFeeRecipient ) external initializer { // Initialize inherited contracts, most base-like -> most derived. __ReentrancyGuard_init(); __ERC2771Context_init(_trustedForwarders); __ERC721_init(_name, _symbol); // Initialize this contract's state. royaltyRecipient = _royaltyRecipient; royaltyBps = uint16(_royaltyBps); platformFeeRecipient = _platformFeeRecipient; platformFeeBps = uint16(_platformFeeBps); primarySaleRecipient = _saleRecipient; contractURI = _contractURI; _owner = _defaultAdmin; _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); _setupRole(MINTER_ROLE, _defaultAdmin); _setupRole(TRANSFER_ROLE, _defaultAdmin); _setupRole(TRANSFER_ROLE, address(0)); } /*/////////////////////////////////////////////////////////////// Generic contract logic //////////////////////////////////////////////////////////////*/ /// @dev Returns the type of the contract. function contractType() external pure returns (bytes32) { return MODULE_TYPE; } /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8) { return uint8(VERSION); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return hasRole(DEFAULT_ADMIN_ROLE, _owner) ? _owner : address(0); } /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 2981 logic //////////////////////////////////////////////////////////////*/ /// @dev Returns the URI for a given tokenId. function tokenURI(uint256 _tokenId) public view override returns (string memory) { for (uint256 i = 0; i < baseURIIndices.length; i += 1) { if (_tokenId < baseURIIndices[i]) { if (encryptedBaseURI[baseURIIndices[i]].length != 0) { return string(abi.encodePacked(baseURI[baseURIIndices[i]], "0")); } else { return string(abi.encodePacked(baseURI[baseURIIndices[i]], _tokenId.toString())); } } } return ""; } /// @dev See ERC 165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721EnumerableUpgradeable, AccessControlEnumerableUpgradeable, IERC165Upgradeable) returns (bool) { return super.supportsInterface(interfaceId) || type(IERC2981Upgradeable).interfaceId == interfaceId; } /// @dev Returns the royalty recipient and amount, given a tokenId and sale price. function royaltyInfo(uint256 tokenId, uint256 salePrice) external view virtual returns (address receiver, uint256 royaltyAmount) { (address recipient, uint256 bps) = getRoyaltyInfoForToken(tokenId); receiver = recipient; royaltyAmount = (salePrice * bps) / MAX_BPS; } /*/////////////////////////////////////////////////////////////// Minting + delayed-reveal logic //////////////////////////////////////////////////////////////*/ /** * @dev Lets an account with `MINTER_ROLE` lazy mint 'n' NFTs. * The URIs for each token is the provided `_baseURIForTokens` + `{tokenId}`. */ function lazyMint( uint256 _amount, string calldata _baseURIForTokens, bytes calldata _encryptedBaseURI ) external onlyRole(MINTER_ROLE) { uint256 startId = nextTokenIdToMint; uint256 baseURIIndex = startId + _amount; nextTokenIdToMint = baseURIIndex; baseURI[baseURIIndex] = _baseURIForTokens; baseURIIndices.push(baseURIIndex); if (_encryptedBaseURI.length != 0) { encryptedBaseURI[baseURIIndex] = _encryptedBaseURI; } emit TokensLazyMinted(startId, startId + _amount - 1, _baseURIForTokens, _encryptedBaseURI); } /// @dev Lets an account with `MINTER_ROLE` reveal the URI for a batch of 'delayed-reveal' NFTs. function reveal(uint256 index, bytes calldata _key) external onlyRole(MINTER_ROLE) returns (string memory revealedURI) { require(index < baseURIIndices.length, "invalid index."); uint256 _index = baseURIIndices[index]; bytes memory encryptedURI = encryptedBaseURI[_index]; require(encryptedURI.length != 0, "nothing to reveal."); revealedURI = string(encryptDecrypt(encryptedURI, _key)); baseURI[_index] = revealedURI; delete encryptedBaseURI[_index]; emit NFTRevealed(_index, revealedURI); return revealedURI; } /// @dev See: https://ethereum.stackexchange.com/questions/69825/decrypt-message-on-chain function encryptDecrypt(bytes memory data, bytes calldata key) public pure returns (bytes memory result) { // Store data length on stack for later use uint256 length = data.length; // solhint-disable-next-line no-inline-assembly assembly { // Set result to free memory pointer result := mload(0x40) // Increase free memory pointer by lenght + 32 mstore(0x40, add(add(result, length), 32)) // Set result length mstore(result, length) } // Iterate over the data stepping by 32 bytes for (uint256 i = 0; i < length; i += 32) { // Generate hash of the key and offset bytes32 hash = keccak256(abi.encodePacked(key, i)); bytes32 chunk; // solhint-disable-next-line no-inline-assembly assembly { // Read 32-bytes data chunk chunk := mload(add(data, add(i, 32))) } // XOR the chunk with hash chunk ^= hash; // solhint-disable-next-line no-inline-assembly assembly { // Write 32-byte encrypted chunk mstore(add(result, add(i, 32)), chunk) } } } /*/////////////////////////////////////////////////////////////// Claim logic //////////////////////////////////////////////////////////////*/ /// @dev Lets an account claim NFTs. function claim( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, bytes32[] calldata _proofs, uint256 _proofMaxQuantityPerTransaction ) external payable nonReentrant { uint256 tokenIdToClaim = nextTokenIdToClaim; // Get the claim conditions. uint256 activeConditionId = getActiveClaimConditionId(); /** * We make allowlist checks (i.e. verifyClaimMerkleProof) before verifying the claim's general * validity (i.e. verifyClaim) because we give precedence to the check of allow list quantity * restriction over the check of the general claim condition's quantityLimitPerTransaction * restriction. */ // Verify inclusion in allowlist. (bool validMerkleProof, uint256 merkleProofIndex) = verifyClaimMerkleProof( activeConditionId, _msgSender(), _quantity, _proofs, _proofMaxQuantityPerTransaction ); // Verify claim validity. If not valid, revert. bool toVerifyMaxQuantityPerTransaction = _proofMaxQuantityPerTransaction == 0; verifyClaim( activeConditionId, _msgSender(), _quantity, _currency, _pricePerToken, toVerifyMaxQuantityPerTransaction ); if (validMerkleProof && _proofMaxQuantityPerTransaction > 0) { /** * Mark the claimer's use of their position in the allowlist. A spot in an allowlist * can be used only once. */ claimCondition.limitMerkleProofClaim[activeConditionId].set(merkleProofIndex); } // If there's a price, collect price. collectClaimPrice(_quantity, _currency, _pricePerToken); // Mint the relevant NFTs to claimer. transferClaimedTokens(_receiver, activeConditionId, _quantity); emit TokensClaimed(activeConditionId, _msgSender(), _receiver, tokenIdToClaim, _quantity); } /// @dev Lets a contract admin (account with `DEFAULT_ADMIN_ROLE`) set claim conditions. function setClaimConditions(ClaimCondition[] calldata _phases, bool _resetClaimEligibility) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 existingStartIndex = claimCondition.currentStartId; uint256 existingPhaseCount = claimCondition.count; /** * `limitLastClaimTimestamp` and `limitMerkleProofClaim` are mappings that use a * claim condition's UID as a key. * * If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim * conditions in `_phases`, effectively resetting the restrictions on claims expressed * by `limitLastClaimTimestamp` and `limitMerkleProofClaim`. */ uint256 newStartIndex = existingStartIndex; if (_resetClaimEligibility) { newStartIndex = existingStartIndex + existingPhaseCount; } claimCondition.count = _phases.length; claimCondition.currentStartId = newStartIndex; uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _phases.length; i++) { require(i == 0 || lastConditionStartTimestamp < _phases[i].startTimestamp, "ST"); uint256 supplyClaimedAlready = claimCondition.phases[newStartIndex + i].supplyClaimed; require(supplyClaimedAlready <= _phases[i].maxClaimableSupply, "max supply claimed already"); claimCondition.phases[newStartIndex + i] = _phases[i]; claimCondition.phases[newStartIndex + i].supplyClaimed = supplyClaimedAlready; lastConditionStartTimestamp = _phases[i].startTimestamp; } /** * Gas refunds (as much as possible) * * If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim * conditions in `_phases`. So, we delete claim conditions with UID < `newStartIndex`. * * If `_resetClaimEligibility == false`, and there are more existing claim conditions * than in `_phases`, we delete the existing claim conditions that don't get replaced * by the conditions in `_phases`. */ if (_resetClaimEligibility) { for (uint256 i = existingStartIndex; i < newStartIndex; i++) { delete claimCondition.phases[i]; delete claimCondition.limitMerkleProofClaim[i]; } } else { if (existingPhaseCount > _phases.length) { for (uint256 i = _phases.length; i < existingPhaseCount; i++) { delete claimCondition.phases[newStartIndex + i]; delete claimCondition.limitMerkleProofClaim[newStartIndex + i]; } } } emit ClaimConditionsUpdated(_phases); } /// @dev Collects and distributes the primary sale value of NFTs being claimed. function collectClaimPrice( uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal { if (_pricePerToken == 0) { return; } uint256 totalPrice = _quantityToClaim * _pricePerToken; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; (address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE); uint256 twFee = (totalPrice * twFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice, "must send total price."); } CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees); CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee); CurrencyTransferLib.transferCurrency( _currency, _msgSender(), primarySaleRecipient, totalPrice - platformFees - twFee ); } /// @dev Transfers the NFTs being claimed. function transferClaimedTokens( address _to, uint256 _conditionId, uint256 _quantityBeingClaimed ) internal { // Update the supply minted under mint condition. claimCondition.phases[_conditionId].supplyClaimed += _quantityBeingClaimed; // if transfer claimed tokens is called when `to != msg.sender`, it'd use msg.sender's limits. // behavior would be similar to `msg.sender` mint for itself, then transfer to `_to`. claimCondition.limitLastClaimTimestamp[_conditionId][_msgSender()] = block.timestamp; walletClaimCount[_msgSender()] += _quantityBeingClaimed; uint256 tokenIdToClaim = nextTokenIdToClaim; for (uint256 i = 0; i < _quantityBeingClaimed; i += 1) { _mint(_to, tokenIdToClaim); tokenIdToClaim += 1; } nextTokenIdToClaim = tokenIdToClaim; } /// @dev Checks a request to claim NFTs against the active claim condition's criteria. function verifyClaim( uint256 _conditionId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, bool verifyMaxQuantityPerTransaction ) public view { ClaimCondition memory currentClaimPhase = claimCondition.phases[_conditionId]; require( _currency == currentClaimPhase.currency && _pricePerToken == currentClaimPhase.pricePerToken, "invalid currency or price." ); // If we're checking for an allowlist quantity restriction, ignore the general quantity restriction. require( _quantity > 0 && (!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction), "invalid quantity." ); require( currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply, "exceed max claimable supply." ); require(nextTokenIdToClaim + _quantity <= nextTokenIdToMint, "not enough minted tokens."); require(maxTotalSupply == 0 || nextTokenIdToClaim + _quantity <= maxTotalSupply, "exceed max total supply."); require( maxWalletClaimCount == 0 || walletClaimCount[_claimer] + _quantity <= maxWalletClaimCount, "exceed claim limit" ); (uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp) = getClaimTimestamp(_conditionId, _claimer); require(lastClaimTimestamp == 0 || block.timestamp >= nextValidClaimTimestamp, "cannot claim."); } /// @dev Checks whether a claimer meets the claim condition's allowlist criteria. function verifyClaimMerkleProof( uint256 _conditionId, address _claimer, uint256 _quantity, bytes32[] calldata _proofs, uint256 _proofMaxQuantityPerTransaction ) public view returns (bool validMerkleProof, uint256 merkleProofIndex) { ClaimCondition memory currentClaimPhase = claimCondition.phases[_conditionId]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (validMerkleProof, merkleProofIndex) = MerkleProof.verify( _proofs, currentClaimPhase.merkleRoot, keccak256(abi.encodePacked(_claimer, _proofMaxQuantityPerTransaction)) ); require(validMerkleProof, "not in whitelist."); require(!claimCondition.limitMerkleProofClaim[_conditionId].get(merkleProofIndex), "proof claimed."); require( _proofMaxQuantityPerTransaction == 0 || _quantity <= _proofMaxQuantityPerTransaction, "invalid quantity proof." ); } } /*/////////////////////////////////////////////////////////////// Getter functions //////////////////////////////////////////////////////////////*/ /// @dev At any given moment, returns the uid for the active claim condition. function getActiveClaimConditionId() public view returns (uint256) { for (uint256 i = claimCondition.currentStartId + claimCondition.count; i > claimCondition.currentStartId; i--) { if (block.timestamp >= claimCondition.phases[i - 1].startTimestamp) { return i - 1; } } revert("!CONDITION."); } /// @dev Returns the royalty recipient and bps for a particular token Id. function getRoyaltyInfoForToken(uint256 _tokenId) public view returns (address, uint16) { RoyaltyInfo memory royaltyForToken = royaltyInfoForToken[_tokenId]; return royaltyForToken.recipient == address(0) ? (royaltyRecipient, uint16(royaltyBps)) : (royaltyForToken.recipient, uint16(royaltyForToken.bps)); } /// @dev Returns the platform fee recipient and bps. function getPlatformFeeInfo() external view returns (address, uint16) { return (platformFeeRecipient, uint16(platformFeeBps)); } /// @dev Returns the default royalty recipient and bps. function getDefaultRoyaltyInfo() external view returns (address, uint16) { return (royaltyRecipient, uint16(royaltyBps)); } /// @dev Returns the timestamp for when a claimer is eligible for claiming NFTs again. function getClaimTimestamp(uint256 _conditionId, address _claimer) public view returns (uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp) { lastClaimTimestamp = claimCondition.limitLastClaimTimestamp[_conditionId][_claimer]; unchecked { nextValidClaimTimestamp = lastClaimTimestamp + claimCondition.phases[_conditionId].waitTimeInSecondsBetweenClaims; if (nextValidClaimTimestamp < lastClaimTimestamp) { nextValidClaimTimestamp = type(uint256).max; } } } /// @dev Returns the claim condition at the given uid. function getClaimConditionById(uint256 _conditionId) external view returns (ClaimCondition memory condition) { condition = claimCondition.phases[_conditionId]; } /// @dev Returns the amount of stored baseURIs function getBaseURICount() external view returns (uint256) { return baseURIIndices.length; } /*/////////////////////////////////////////////////////////////// Setter functions //////////////////////////////////////////////////////////////*/ /// @dev Lets a contract admin set a claim count for a wallet. function setWalletClaimCount(address _claimer, uint256 _count) external onlyRole(DEFAULT_ADMIN_ROLE) { walletClaimCount[_claimer] = _count; emit WalletClaimCountUpdated(_claimer, _count); } /// @dev Lets a contract admin set a maximum number of NFTs that can be claimed by any wallet. function setMaxWalletClaimCount(uint256 _count) external onlyRole(DEFAULT_ADMIN_ROLE) { maxWalletClaimCount = _count; emit MaxWalletClaimCountUpdated(_count); } /// @dev Lets a contract admin set the global maximum supply for collection's NFTs. function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_maxTotalSupply < nextTokenIdToMint, "existing > desired max supply"); maxTotalSupply = _maxTotalSupply; emit MaxTotalSupplyUpdated(_maxTotalSupply); } /// @dev Lets a contract admin set the recipient for all primary sales. function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) { primarySaleRecipient = _saleRecipient; emit PrimarySaleRecipientUpdated(_saleRecipient); } /// @dev Lets a contract admin update the default royalty recipient and bps. function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_royaltyBps <= MAX_BPS, "> MAX_BPS"); royaltyRecipient = _royaltyRecipient; royaltyBps = uint16(_royaltyBps); emit DefaultRoyalty(_royaltyRecipient, _royaltyBps); } /// @dev Lets a contract admin set the royalty recipient and bps for a particular token Id. function setRoyaltyInfoForToken( uint256 _tokenId, address _recipient, uint256 _bps ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_bps <= MAX_BPS, "> MAX_BPS"); royaltyInfoForToken[_tokenId] = RoyaltyInfo({ recipient: _recipient, bps: _bps }); emit RoyaltyForToken(_tokenId, _recipient, _bps); } /// @dev Lets a contract admin update the platform fee recipient and bps function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_platformFeeBps <= MAX_BPS, "> MAX_BPS."); platformFeeBps = uint16(_platformFeeBps); platformFeeRecipient = _platformFeeRecipient; emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps); } /// @dev Lets a contract admin set a new owner for the contract. The new owner must be a contract admin. function setOwner(address _newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) { require(hasRole(DEFAULT_ADMIN_ROLE, _newOwner), "!ADMIN"); address _prevOwner = _owner; _owner = _newOwner; emit OwnerUpdated(_prevOwner, _newOwner); } /// @dev Lets a contract admin set the URI for contract-level metadata. function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { contractURI = _uri; } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ /// @dev Burns `tokenId`. See {ERC721-_burn}. function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "caller not owner nor approved"); _burn(tokenId); } /// @dev See {ERC721-_beforeTokenTransfer}. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); // if transfer is restricted on the contract, we still want to allow burning and minting if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "!TRANSFER_ROLE"); } } function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { return ERC2771ContextUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { return ERC2771ContextUpgradeable._msgData(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol) pragma solidity ^0.8.0; /** * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. * Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor]. */ library BitMapsUpgradeable { struct BitMap { mapping(uint256 => uint256) _data; } /** * @dev Returns whether the bit at `index` is set. */ function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); return bitmap._data[bucket] & mask != 0; } /** * @dev Sets the bit at `index` to the boolean `value`. */ function setTo( BitMap storage bitmap, uint256 index, bool value ) internal { if (value) { set(bitmap, index); } else { unset(bitmap, index); } } /** * @dev Sets the bit at `index`. */ function set(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] |= mask; } /** * @dev Unsets the bit at `index`. */ function unset(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] &= ~mask; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol) pragma solidity ^0.8.0; import "./AddressUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Provides a function to batch together multiple calls in a single external call. * * _Available since v4.1._ */ abstract contract MulticallUpgradeable is Initializable { function __Multicall_init() internal onlyInitializing { } function __Multicall_init_unchained() internal onlyInitializing { } /** * @dev Receives and executes a batch of function calls on this contract. */ function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = _functionDelegateCall(address(this), data[i]); } return results; } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ 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: Apache-2.0 pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "../IThirdwebContract.sol"; import "../IThirdwebPlatformFee.sol"; import "../IThirdwebPrimarySale.sol"; import "../IThirdwebRoyalty.sol"; import "../IThirdwebOwnable.sol"; import "./IDropClaimCondition.sol"; /** * Thirdweb's 'Drop' contracts are distribution mechanisms for tokens. The * `DropERC721` contract is a distribution mechanism for ERC721 tokens. * * A minter wallet (i.e. holder of `MINTER_ROLE`) can (lazy)mint 'n' tokens * at once by providing a single base URI for all tokens being lazy minted. * The URI for each of the 'n' tokens lazy minted is the provided base URI + * `{tokenId}` of the respective token. (e.g. "ipsf://Qmece.../1"). * * A minter can choose to lazy mint 'delayed-reveal' tokens. More on 'delayed-reveal' * tokens in [this article](https://blog.thirdweb.com/delayed-reveal-nfts). * * A contract admin (i.e. holder of `DEFAULT_ADMIN_ROLE`) can create claim conditions * with non-overlapping time windows, and accounts can claim the tokens according to * restrictions defined in the claim condition that is active at the time of the transaction. */ interface IDropERC721 is IThirdwebContract, IThirdwebOwnable, IThirdwebRoyalty, IThirdwebPrimarySale, IThirdwebPlatformFee, IERC721Upgradeable, IDropClaimCondition { /// @dev Emitted when tokens are claimed. event TokensClaimed( uint256 indexed claimConditionIndex, address indexed claimer, address indexed receiver, uint256 startTokenId, uint256 quantityClaimed ); /// @dev Emitted when tokens are lazy minted. event TokensLazyMinted(uint256 startTokenId, uint256 endTokenId, string baseURI, bytes encryptedBaseURI); /// @dev Emitted when the URI for a batch of 'delayed-reveal' NFTs is revealed. event NFTRevealed(uint256 endTokenId, string revealedURI); /// @dev Emitted when new claim conditions are set. event ClaimConditionsUpdated(ClaimCondition[] claimConditions); /// @dev Emitted when the global max supply of tokens is updated. event MaxTotalSupplyUpdated(uint256 maxTotalSupply); /// @dev Emitted when the wallet claim count for an address is updated. event WalletClaimCountUpdated(address indexed wallet, uint256 count); /// @dev Emitted when the global max wallet claim count is updated. event MaxWalletClaimCountUpdated(uint256 count); /** * @notice Lets an account with `MINTER_ROLE` lazy mint 'n' NFTs. * The URIs for each token is the provided `_baseURIForTokens` + `{tokenId}`. * * @param amount The amount of NFTs to lazy mint. * @param baseURIForTokens The URI for the NFTs to lazy mint. If lazy minting * 'delayed-reveal' NFTs, the is a URI for NFTs in the * un-revealed state. * @param encryptedBaseURI If lazy minting 'delayed-reveal' NFTs, this is the * result of encrypting the URI of the NFTs in the revealed * state. */ function lazyMint( uint256 amount, string calldata baseURIForTokens, bytes calldata encryptedBaseURI ) external; /** * @notice Lets an account claim a given quantity of NFTs. * * @param receiver The receiver of the NFTs to claim. * @param quantity The quantity of NFTs to claim. * @param currency The currency in which to pay for the claim. * @param pricePerToken The price per token to pay for the claim. * @param proofs The proof of the claimer's inclusion in the merkle root allowlist * of the claim conditions that apply. * @param proofMaxQuantityPerTransaction (Optional) The maximum number of NFTs an address included in an * allowlist can claim. */ function claim( address receiver, uint256 quantity, address currency, uint256 pricePerToken, bytes32[] calldata proofs, uint256 proofMaxQuantityPerTransaction ) external payable; /** * @notice Lets a contract admin (account with `DEFAULT_ADMIN_ROLE`) set claim conditions. * * @param phases Claim conditions in ascending order by `startTimestamp`. * @param resetClaimEligibility Whether to reset `limitLastClaimTimestamp` and * `limitMerkleProofClaim` values when setting new * claim conditions. */ function setClaimConditions(ClaimCondition[] calldata phases, bool resetClaimEligibility) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface ITWFee { function getFeeInfo(address _proxy, uint256 _type) external view returns (address recipient, uint256 bps); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (metatx/ERC2771Context.sol) pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; /** * @dev Context variant with ERC2771 support. */ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable { mapping(address => bool) private _trustedForwarder; function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing { __Context_init_unchained(); __ERC2771Context_init_unchained(trustedForwarder); } function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing { for (uint256 i = 0; i < trustedForwarder.length; i++) { _trustedForwarder[trustedForwarder[i]] = true; } } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return _trustedForwarder[forwarder]; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } uint256[49] private __gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; // Helper interfaces import { IWETH } from "../interfaces/IWETH.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; library CurrencyTransferLib { using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev The address interpreted as native token of the chain. address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Transfers a given amount of currency. function transferCurrency( address _currency, address _from, address _to, uint256 _amount ) internal { if (_amount == 0) { return; } if (_currency == NATIVE_TOKEN) { safeTransferNativeToken(_to, _amount); } else { safeTransferERC20(_currency, _from, _to, _amount); } } /// @dev Transfers a given amount of currency. (With native token wrapping) function transferCurrencyWithWrapper( address _currency, address _from, address _to, uint256 _amount, address _nativeTokenWrapper ) internal { if (_amount == 0) { return; } if (_currency == NATIVE_TOKEN) { if (_from == address(this)) { // withdraw from weth then transfer withdrawn native token to recipient IWETH(_nativeTokenWrapper).withdraw(_amount); safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper); } else if (_to == address(this)) { // store native currency in weth require(_amount == msg.value, "msg.value != amount"); IWETH(_nativeTokenWrapper).deposit{ value: _amount }(); } else { safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper); } } else { safeTransferERC20(_currency, _from, _to, _amount); } } /// @dev Transfer `amount` of ERC20 token from `from` to `to`. function safeTransferERC20( address _currency, address _from, address _to, uint256 _amount ) internal { if (_from == _to) { return; } if (_from == address(this)) { IERC20Upgradeable(_currency).safeTransfer(_to, _amount); } else { IERC20Upgradeable(_currency).safeTransferFrom(_from, _to, _amount); } } /// @dev Transfers `amount` of native token to `to`. function safeTransferNativeToken(address to, uint256 value) internal { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool success, ) = to.call{ value: value }(""); require(success, "native token transfer failed"); } /// @dev Transfers `amount` of native token to `to`. (With native token wrapping) function safeTransferNativeTokenWithWrapper( address to, uint256 value, address _nativeTokenWrapper ) internal { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool success, ) = to.call{ value: value }(""); if (!success) { IWETH(_nativeTokenWrapper).deposit{ value: value }(); IERC20Upgradeable(_nativeTokenWrapper).safeTransfer(to, value); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; library FeeType { uint256 internal constant PRIMARY_SALE = 0; uint256 internal constant MARKET_SALE = 1; uint256 internal constant SPLIT = 2; } // SPDX-License-Identifier: MIT // Modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/utils/cryptography/MerkleProof.sol // Copied from https://github.com/ensdomains/governance/blob/master/contracts/MerkleProof.sol pragma solidity ^0.8.11; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. * * Source: https://github.com/ensdomains/governance/blob/master/contracts/MerkleProof.sol */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool, uint256) { bytes32 computedHash = leaf; uint256 index = 0; for (uint256 i = 0; i < proof.length; i++) { index *= 2; bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); index += 1; } } // Check if the computed hash (root) is equal to the provided root return (computedHash == root, index); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __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); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = 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); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(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 {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 proxied contracts do not make use of 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 (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/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 (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; 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 { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // 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 { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // 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 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IThirdwebContract { /// @dev Returns the module type of the contract. function contractType() external pure returns (bytes32); /// @dev Returns the version of the contract. function contractVersion() external pure returns (uint8); /// @dev Returns the metadata URI of the contract. function contractURI() external view returns (string memory); /** * @dev Sets contract URI for the storefront-level metadata of the contract. * Only module admin can call this function. */ function setContractURI(string calldata _uri) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IThirdwebPlatformFee { /// @dev Returns the platform fee bps and recipient. function getPlatformFeeInfo() external view returns (address, uint16); /// @dev Lets a module admin update the fees on primary sales. function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external; /// @dev Emitted when fee on primary sales is updated. event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IThirdwebPrimarySale { /// @dev The adress that receives all primary sales value. function primarySaleRecipient() external view returns (address); /// @dev Lets a module admin set the default recipient of all primary sales. function setPrimarySaleRecipient(address _saleRecipient) external; /// @dev Emitted when a new sale recipient is set. event PrimarySaleRecipientUpdated(address indexed recipient); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; interface IThirdwebRoyalty is IERC2981Upgradeable { struct RoyaltyInfo { address recipient; uint256 bps; } /// @dev Returns the royalty recipient and fee bps. function getDefaultRoyaltyInfo() external view returns (address, uint16); /// @dev Lets a module admin update the royalty bps and recipient. function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) external; /// @dev Lets a module admin set the royalty recipient for a particular token Id. function setRoyaltyInfoForToken( uint256 tokenId, address recipient, uint256 bps ) external; /// @dev Returns the royalty recipient for a particular token Id. function getRoyaltyInfoForToken(uint256 tokenId) external view returns (address, uint16); /// @dev Emitted when royalty info is updated. event DefaultRoyalty(address newRoyaltyRecipient, uint256 newRoyaltyBps); /// @dev Emitted when royalty recipient for tokenId is set event RoyaltyForToken(uint256 indexed tokenId, address royaltyRecipient, uint256 royaltyBps); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IThirdwebOwnable { /// @dev Returns the owner of the contract. function owner() external view returns (address); /// @dev Lets a module admin set a new owner for the contract. The new owner must be a module admin. function setOwner(address _newOwner) external; /// @dev Emitted when a new Owner is set. event OwnerUpdated(address prevOwner, address newOwner); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol"; /** * Thirdweb's 'Drop' contracts are distribution mechanisms for tokens. * * A contract admin (i.e. a holder of `DEFAULT_ADMIN_ROLE`) can set a series of claim conditions, * ordered by their respective `startTimestamp`. A claim condition defines criteria under which * accounts can mint tokens. Claim conditions can be overwritten or added to by the contract admin. * At any moment, there is only one active claim condition. */ interface IDropClaimCondition { /** * @notice The criteria that make up a claim condition. * * @param startTimestamp The unix timestamp after which the claim condition applies. * The same claim condition applies until the `startTimestamp` * of the next claim condition. * * @param maxClaimableSupply The maximum total number of tokens that can be claimed under * the claim condition. * * @param supplyClaimed At any given point, the number of tokens that have been claimed * under the claim condition. * * @param quantityLimitPerTransaction The maximum number of tokens that can be claimed in a single * transaction. * * @param waitTimeInSecondsBetweenClaims The least number of seconds an account must wait after claiming * tokens, to be able to claim tokens again. * * @param merkleRoot The allowlist of addresses that can claim tokens under the claim * condition. * * @param pricePerToken The price required to pay per token claimed. * * @param currency The currency in which the `pricePerToken` must be paid. */ struct ClaimCondition { uint256 startTimestamp; uint256 maxClaimableSupply; uint256 supplyClaimed; uint256 quantityLimitPerTransaction; uint256 waitTimeInSecondsBetweenClaims; bytes32 merkleRoot; uint256 pricePerToken; address currency; } /** * @notice The set of all claim conditions, at any given moment. * Claim Phase ID = [currentStartId, currentStartId + length - 1]; * * @param currentStartId The uid for the first claim condition amongst the current set of * claim conditions. The uid for each next claim condition is one * more than the previous claim condition's uid. * * @param count The total number of phases / claim conditions in the list * of claim conditions. * * @param phases The claim conditions at a given uid. Claim conditions * are ordered in an ascending order by their `startTimestamp`. * * @param limitLastClaimTimestamp Map from an account and uid for a claim condition, to the last timestamp * at which the account claimed tokens under that claim condition. * * @param limitMerkleProofClaim Map from a claim condition uid to whether an address in an allowlist * has already claimed tokens i.e. used their place in the allowlist. */ struct ClaimConditionList { uint256 currentStartId; uint256 count; mapping(uint256 => ClaimCondition) phases; mapping(uint256 => mapping(address => uint256)) limitLastClaimTimestamp; mapping(uint256 => BitMapsUpgradeable.BitMap) limitMerkleProofClaim; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.11; interface IWETH { function deposit() external payable; function withdraw(uint256 amount) external; function transfer(address to, uint256 value) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
Checks a request to claim NFTs against the active claim condition's criteria. If we're checking for an allowlist quantity restriction, ignore the general quantity restriction.
function verifyClaim( uint256 _conditionId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, bool verifyMaxQuantityPerTransaction ) public view { ClaimCondition memory currentClaimPhase = claimCondition.phases[_conditionId]; require( _currency == currentClaimPhase.currency && _pricePerToken == currentClaimPhase.pricePerToken, "invalid currency or price." ); require( _quantity > 0 && (!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction), "invalid quantity." ); require( currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply, "exceed max claimable supply." ); require(nextTokenIdToClaim + _quantity <= nextTokenIdToMint, "not enough minted tokens."); require(maxTotalSupply == 0 || nextTokenIdToClaim + _quantity <= maxTotalSupply, "exceed max total supply."); require( maxWalletClaimCount == 0 || walletClaimCount[_claimer] + _quantity <= maxWalletClaimCount, "exceed claim limit" ); (uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp) = getClaimTimestamp(_conditionId, _claimer); require(lastClaimTimestamp == 0 || block.timestamp >= nextValidClaimTimestamp, "cannot claim."); }
94,631
./full_match/1/0x36C437d15A8d83F3D45de0EdAC22659559861418/sources/contracts/escrow/Escrow.sol
Change the address of the wallet for receiving fees (owner only) _wallet Address of the wallet for receiving fees/
function changeWallet(address _wallet) external onlyOwner { require(_wallet != address(0), "Escrow: Zero address is not allowed"); ntzcWallet = _wallet; emit FeeWalletChanged(_wallet); }
17,043,622
./full_match/80001/0xbdEa5eBd0968EB86dfEC0a775683f89059f405be/sources/SmartMining.sol
Check if we know this user Return all the tokens in the stakedToken Array for this user that are not -1
function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } }
842,215
pragma solidity ^0.4.24; // File: contracts/AZTEC/AZTEC.sol library AZTECInterface { function validateJoinSplit(bytes32[6][], uint, uint, bytes32[4]) external pure returns (bool) {} } /** * @title Library to validate AZTEC zero-knowledge proofs * @author Zachary Williamson, AZTEC * @dev Don't include this as an internal library. This contract uses a static memory table to cache elliptic curve primitives and hashes. * Calling this internally from another function will lead to memory mutation and undefined behaviour. * The intended use case is to call this externally via `staticcall`. External calls to OptimizedAZTEC can be treated as pure functions as this contract contains no storage and makes no external calls (other than to precompiles) * Copyright Spilbury Holdings Ltd 2018. All rights reserved. * We will be releasing AZTEC as an open-source protocol that provides efficient transaction privacy for Ethereum. * Our full vision of the protocol includes confidential cross-asset interactions via our family of AZTEC zero-knowledge proofs * and the AZTEC token standard, stay tuned for updates! **/ contract AZTEC { /** * @dev AZTEC will take any transaction sent to it and attempt to validate a zero knowledge proof. * If the proof is not valid, the transaction will throw. * @notice See AZTECInterface for how method calls should be constructed. * 'Cost' of raw elliptic curve primitives for a transaction: 260,700 gas + (124,500 * number of input notes) + (167,600 * number of output notes). * For a basic 'joinSplit' with 2 inputs and 2 outputs = 844,900 gas. * AZTEC is written in YUL to enable manual memory management and for other efficiency savings. **/ function() external payable { assembly { // We don't check for function signatures, there's only one function that ever gets called: validateJoinSplit() // We still assume calldata is offset by 4 bytes so that we can represent this contract through a compatible ABI validateJoinSplit() // should not get here mstore(0x00, 404) revert(0x00, 0x20) /** * @dev Validate an AZTEC protocol JoinSplit zero-knowledge proof * Calldata Map is * 0x04:0x24 = calldata location of start of ```note``` dynamic array * 0x24:0x44 = m, which defines the index separator between input notes ando utput notes * 0x44:0x64 = Fiat-Shamir heuristicified random challenge * 0x64:0xe4 = G2 element t2, the trusted setup public key * 0xe4:0x104 = start of ```note``` dynamic array, contains the size of the array (```n```) * Subsequent calldata arranged in 0xc0 sized blocks of data, each representing an AZTEC commitment and zero-knowledge proof variables * * Note data map (uint[6]) is * 0x00:0x20 = Z_p element \bar{k}_i * 0x20:0x40 = Z_p element \bar{a}_i * 0x40:0x80 = G1 element \gamma_i * 0x80:0xc0 = G1 element \sigma_i * * The last element in the note array is special and contains the following: * 0x00:0x20 = Z_p element k_{public} * 0x20:0x40 = Z_p element \bar{a}_i * 0x40:0x60 = G1 element \gamma_i * 0x60-0x80 = G1 element \sigma_i * We can recover \bar{k}_{n-1} from the homomorphic sum condition \sum_{i=0}^{m-1}\bar{k}_i = \sum_{i=m}^{n-1}\bar{k}_i + k_{public} * So we use the empty slot to store k_{public}, which represents any public 'value' being blinded into zero-knowledge notes * * We use a hard-coded memory map to reduce gas costs - if this is not called as an external contract then terrible things will happen! * 0x00:0x20 = scratch data to store result of keccak256 calls * 0x20:0x80 = scratch data to store \gamma_i and a multiplication scalar * 0x80:0xc0 = x-coordinate of generator h * 0xc0:0xe0 = y-coordinate of generator h * 0xe0:0x100 = scratch data to store a scalar we plan to multiply h by * 0x100:0x160 = scratch data to store \sigma_i and a multiplication scalar * 0x160:0x1a0 = stratch data to store result of G1 point additions * 0x1a0:0x1c0 = scratch data to store result of \sigma_i^{-cx_{i-m-1}} * 0x1c0:0x200 = location of pairing accumulator \sigma_{acc}, where \sigma_{acc} = \prod_{i=m}^{n-1}\sigma_i^{cx_{i-m-1}} * 0x220:0x260 = scratch data to store \gamma_i^{cx_{i-m-1}} * 0x260:0x2a0 = location of pairing accumulator \gamma_{acc}, where \gamma_{acc} = \prod_{i=m}^{n-1}\gamma_i^{cx_{i-m-1}} * 0x2a0:0x2c0 = msg.sender (contract should be called via delegatecall/staticcall) * 0x2c0:0x2e0 = kn (memory used to reconstruct hash starts here) * 0x2e0:0x300 = m * 0x300:??? = block of memory that contains (\gamma_i, \sigma_i)_{i=0}^{n-1} concatenated with (B_i)_{i=0}^{n-1} **/ function validateJoinSplit() { mstore(0x80, 7673901602397024137095011250362199966051872585513276903826533215767972925880) // h_x mstore(0xa0, 8489654445897228341090914135473290831551238522473825886865492707826370766375) // h_y let notes := add(0x04, calldataload(0x04)) let m := calldataload(0x24) let n := calldataload(notes) let gen_order := 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 let challenge := mod(calldataload(0x44), gen_order) // validate m <= n if gt(m, n) { mstore(0x00, 404) revert(0x00, 0x20) } // recover k_{public} and calculate k_{public} let kn := calldataload(sub(calldatasize, 0xc0)) // add kn and m to final hash table mstore(0x2a0, caller) mstore(0x2c0, kn) mstore(0x2e0, m) kn := mulmod(sub(gen_order, kn), challenge, gen_order) // we actually want c*k_{public} hashCommitments(notes, n) let b := add(0x300, mul(n, 0x80)) // Iterate over every note and calculate the blinding factor B_i = \gamma_i^{kBar}h^{aBar}\sigma_i^{-c}. // We use the AZTEC protocol pairing optimization to reduce the number of pairing comparisons to 1, which adds some minor alterations for { let i := 0 } lt(i, n) { i := add(i, 0x01) } { // Get the calldata index of this note let noteIndex := add(add(notes, 0x20), mul(i, 0xc0)) // Define variables k, a and c. // If i <= m then // k = kBar_i // a = aBar_i // c = challenge // If i > m then we add a modification for the pairing optimization // k = kBar_i * x_i // a = aBar_i * x_i // c = challenge * x_i // Set j = i - (m + 1). // x_0 = 1 // x_1 = keccak256(input string) // all other x_{j} = keccak256(x_{j-1}) // The reason for doing this is that the point \sigma_i^{-cx_j} can be re-used in the pairing check // Instead of validating e(\gamma_i, t_2) == e(\sigma_i, g_2) for all i = [m+1,\ldots,n] // We instead validate e(\Pi_{i=m+1}^{n}\gamma_i^{-cx_j}, t_2) == e(\Pi_{i=m+1}^{n}\sigma_i^{cx_j}, g_2). // x_j is a pseudorandom variable whose entropy source is the input string, allowing for // a sum of commitment points to be evaluated in one pairing comparison let k let a := calldataload(add(noteIndex, 0x20)) let c := challenge // We don't transmit kBar_{n-1} in the proof to save space, instead we derive it // As per the homomorphic sum condition: \sum_{i=0}^{m-1}\bar{k}_i = \sum_{i=m}^{n-1}\bar{k}_i + k_{public}c, // We can recover \bar{k}_{n-1}. // If m=n then \bar{k}_{n-1} = \sum_{i=0}^{n-1}\bar{k}_i + k_{public} // else \bar{k}_{n-1} = \sum_{i=0}^{m-1}\bar{k}_i - \sum_{i=m}^{n-1}\bar{k}_i - k_{public} switch eq(add(i, 0x01), n) case 1 { k := kn // if all notes are input notes, invert k if eq(m, n) { k := sub(gen_order, k) } } case 0 { k := calldataload(noteIndex) } // Check this commitment is well formed... validateCommitment(noteIndex, k, a) // If i > m then this is an output note. // Set k = kx_j, a = ax_j, c = cx_j, where j = i - (m+1) switch gt(add(i, 0x01), m) case 1 { // before we update k, update kn = \sum_{i=0}^{m-1}k_i - \sum_{i=m}^{n-1}k_i kn := addmod(kn, sub(gen_order, k), gen_order) let x := mod(mload(0x00), gen_order) k := mulmod(k, x, gen_order) a := mulmod(a, x, gen_order) c := mulmod(challenge, x, gen_order) // calculate x_{j+1} mstore(0x00, keccak256(0x00, 0x20)) } case 0 { // nothing to do here except update kn = \sum_{i=0}^{m-1}k_i - \sum_{i=m}^{n-1}k_i kn := addmod(kn, k, gen_order) } // Calculate the G1 element \gamma_i^{k}h^{a}\sigma_i^{-c} = B_i // Memory map: // 0x20: \gamma_iX // 0x40: \gamma_iY // 0x60: k_i // 0x80: hX // 0xa0: hY // 0xc0: a_i // 0xe0: \sigma_iX // 0x100: \sigma_iY // 0x120: -c calldatacopy(0xe0, add(noteIndex, 0x80), 0x40) calldatacopy(0x20, add(noteIndex, 0x40), 0x40) mstore(0x120, sub(gen_order, c)) mstore(0x60, k) mstore(0xc0, a) // Call bn128 scalar multiplication precompiles // Represent point + multiplication scalar in 3 consecutive blocks of memory // Store \sigma_i^{-c} at 0x1a0:0x200 // Store \gamma_i^{k} at 0x120:0x160 // Store h^{a} at 0x160:0x1a0 let result := staticcall(gas, 7, 0xe0, 0x60, 0x1a0, 0x40) result := and(result, staticcall(gas, 7, 0x20, 0x60, 0x120, 0x40)) result := and(result, staticcall(gas, 7, 0x80, 0x60, 0x160, 0x40)) // Call bn128 group addition precompiles // \gamma_i^{k} and h^{a} in memory block 0x120:0x1a0 // Store result of addition at 0x160:0x1a0 result := and(result, staticcall(gas, 6, 0x120, 0x80, 0x160, 0x40)) // \gamma_i^{k}h^{a} and \sigma^{-c} in memory block 0x160:0x1e0 // Store resulting point B at memory index b result := and(result, staticcall(gas, 6, 0x160, 0x80, b, 0x40)) // We have \sigma^{-c} at 0x1a0:0x200 // And \sigma_{acc} at 0x1e0:0x200 // If i = m + 1 (i.e. first output note) // then we set \gamma_{acc} and \sigma_{acc} to \gamma_i, -\sigma_i if eq(i, m) { mstore(0x260, mload(0x20)) mstore(0x280, mload(0x40)) mstore(0x1e0, mload(0xe0)) mstore(0x200, sub(0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47, mload(0x100))) } // If i > m + 1 (i.e. subsequent output notes) // then we add \sigma^{-c} and \sigma_{acc} and store result at \sigma_{acc} (0x1e0:0x200) // we then calculate \gamma^{cx} and add into \gamma_{acc} if gt(i, m) { mstore(0x60, c) result := and(result, staticcall(gas, 7, 0x20, 0x60, 0x220, 0x40)) // \gamma_i^{cx} now at 0x220:0x260, \gamma_{acc} is at 0x260:0x2a0 result := and(result, staticcall(gas, 6, 0x220, 0x80, 0x260, 0x40)) // add \sigma_i^{-cx} and \sigma_{acc} into \sigma_{acc} at 0x1e0 result := and(result, staticcall(gas, 6, 0x1a0, 0x80, 0x1e0, 0x40)) } // throw transaction if any calls to precompiled contracts failed if iszero(result) { mstore(0x00, 400) revert(0x00, 0x20) } b := add(b, 0x40) // increase B pointer by 2 words } // If the AZTEC protocol is implemented correctly then any input notes were previously outputs of // a JoinSplit transaction. We can inductively assume that all input notes are well-formed AZTEC commitments and do not need to validate the implicit range proof // This is not the case for any output commitments, so if (m < n) call validatePairing() if lt(m, n) { validatePairing(0x64) } // We now have the note commitments and the calculated blinding factors in a block of memory // starting at 0x2a0, of size (b - 0x2a0). // Hash this block to reconstruct the initial challenge and validate that they match let expected := mod(keccak256(0x2a0, sub(b, 0x2a0)), gen_order) if iszero(eq(expected, challenge)) { // No! Bad! No soup for you! mstore(0x00, 404) revert(0x00, 0x20) } // Great! All done. This is a valid proof so return ```true``` mstore(0x00, 0x01) return(0x00, 0x20) } /** * @dev evaluate if e(P1, t2) . e(P2, g2) == 0. * @notice we don't hard-code t2 so that contracts that call this library can use different trusted setups. **/ function validatePairing(t2) { let field_order := 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 let t2_x_1 := calldataload(t2) let t2_x_2 := calldataload(add(t2, 0x20)) let t2_y_1 := calldataload(add(t2, 0x40)) let t2_y_2 := calldataload(add(t2, 0x60)) // check provided setup pubkey is not zero or g2 if or(or(or(or(or(or(or( iszero(t2_x_1), iszero(t2_x_2)), iszero(t2_y_1)), iszero(t2_y_2)), eq(t2_x_1, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed)), eq(t2_x_2, 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2)), eq(t2_y_1, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa)), eq(t2_y_2, 0x90689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b)) { mstore(0x00, 400) revert(0x00, 0x20) } // store coords in memory // indices are a bit off, scipr lab's libff limb ordering (c0, c1) is opposite to what precompile expects // We can overwrite the memory we used previously as this function is called at the end of the validation routine. mstore(0x20, mload(0x1e0)) // sigma accumulator x mstore(0x40, mload(0x200)) // sigma accumulator y mstore(0x80, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed) mstore(0x60, 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2) mstore(0xc0, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa) mstore(0xa0, 0x90689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b) mstore(0xe0, mload(0x260)) // gamma accumulator x mstore(0x100, mload(0x280)) // gamma accumulator y mstore(0x140, t2_x_1) mstore(0x120, t2_x_2) mstore(0x180, t2_y_1) mstore(0x160, t2_y_2) let success := staticcall(gas, 8, 0x20, 0x180, 0x20, 0x20) if or(iszero(success), iszero(mload(0x20))) { mstore(0x00, 400) revert(0x00, 0x20) } } /** * @dev check that this note's points are on the altbn128 curve(y^2 = x^3 + 3) * and that signatures 'k' and 'a' are modulo the order of the curve. Transaction will throw if this is not the case. * @param note the calldata loation of the note **/ function validateCommitment(note, k, a) { let gen_order := 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 let field_order := 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 let gammaX := calldataload(add(note, 0x40)) let gammaY := calldataload(add(note, 0x60)) let sigmaX := calldataload(add(note, 0x80)) let sigmaY := calldataload(add(note, 0xa0)) if iszero( and( and( and( eq(mod(a, gen_order), a), // a is modulo generator order? gt(a, 1) // can't be 0 or 1 either! ), and( eq(mod(k, gen_order), k), // k is modulo generator order? gt(k, 1) // and not 0 or 1 ) ), and( eq( // y^2 ?= x^3 + 3 addmod(mulmod(mulmod(sigmaX, sigmaX, field_order), sigmaX, field_order), 3, field_order), mulmod(sigmaY, sigmaY, field_order) ), eq( // y^2 ?= x^3 + 3 addmod(mulmod(mulmod(gammaX, gammaX, field_order), gammaX, field_order), 3, field_order), mulmod(gammaY, gammaY, field_order) ) ) ) ) { mstore(0x00, 400) revert(0x00, 0x20) } } /** * @dev Calculate the keccak256 hash of the commitments for both input notes and output notes. * This is used both as an input to validate the challenge `c` and also to generate pseudorandom relationships * between commitments for different outputNotes, so that we can combine them into a single multi-exponentiation for the purposes of validating the bilinear pairing relationships. * @param notes calldata location notes * @param n number of notes **/ function hashCommitments(notes, n) { for { let i := 0 } lt(i, n) { i := add(i, 0x01) } { let index := add(add(notes, mul(i, 0xc0)), 0x60) calldatacopy(add(0x300, mul(i, 0x80)), index, 0x80) } mstore(0x00, keccak256(0x300, mul(n, 0x80))) } } } } // File: contracts/AZTEC/AZTECERC20Bridge.sol /** * @title ERC20 interface * @dev https://github.com/ethereum/EIPs/issues/20 **/ contract ERC20Interface { function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } /** * @title AZTEC token, providing a confidential representation of an ERC20 token * @author Zachary Williamson, AZTEC * Copyright Spilsbury Holdings Ltd 2018. All rights reserved. * We will be releasing AZTEC as an open-source protocol that provides efficient transaction privacy for Ethereum. * Our full vision of the protocol includes confidential cross-asset interactions via our family of AZTEC zero-knowledge proofs * and the AZTEC token standard, stay tuned for updates! **/ contract AZTECERC20Bridge { bytes32[4] setupPubKey; bytes32 domainHash; uint private constant groupModulusBoundary = 10944121435919637611123202872628637544274182200208017171849102093287904247808; uint private constant groupModulus = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint public scalingFactor; mapping(bytes32 => address) public noteRegistry; ERC20Interface token; event Created(bytes32 domainHash, address contractAddress); event ConfidentialTransfer(); /** * @dev contract constructor. * @param _setupPubKey the trusted setup public key (group element of group G2) * @param _token the address of the ERC20 token being attached to * @param _scalingFactor the mapping from note value -> ERC20 token value. * AZTEC notes have a range between 0 and 2^{25}-1 and ERC20 tokens range between 0 and 2^{255} - 1 * so we don't want to directly map note value : token value **/ constructor(bytes32[4] _setupPubKey, address _token, uint256 _scalingFactor, uint256 _chainId) public { setupPubKey = _setupPubKey; token = ERC20Interface(_token); scalingFactor = _scalingFactor; bytes32 _domainHash; assembly { let m := mload(0x40) mstore(m, 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f) // "EIP712Domain(string name, string version, uint256 chainId, address verifyingContract)" mstore(add(m, 0x20), 0x60d177492a60de7c666b3e3d468f14d59def1d4b022d08b6adf554d88da60d63) // name = "AZTECERC20BRIDGE_DOMAIN" mstore(add(m, 0x40), 0x28a43689b8932fb9695c28766648ed3d943ff8a6406f8f593738feed70039290) // version = "0.1.1" mstore(add(m, 0x60), _chainId) // chain id mstore(add(m, 0x80), address) // verifying contract _domainHash := keccak256(m, 0xa0) } domainHash = _domainHash; emit Created(_domainHash, this); } /** * @dev Determine validity of an input note and remove from note registry * 1. validate that the note is signed by the note owner * 2. validate that the note exists in the note registry * * Note signature is EIP712 signature (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md) over the following struct * struct AZTEC_NOTE_SIGNATURE { * bytes32[4] note; * uint256 challenge; * address sender; * }; * @param note AZTEC confidential note being destroyed * @param signature ECDSA signature from note owner * @param challenge AZTEC zero-knowledge proof challenge * @param domainHashT Temporary holding ```domainHash``` (to minimize # of sload ops) **/ function validateInputNote(bytes32[6] note, bytes32[3] signature, uint challenge, bytes32 domainHashT) internal { bytes32 noteHash; bytes32 signatureMessage; assembly { let m := mload(0x40) mstore(m, mload(add(note, 0x40))) mstore(add(m, 0x20), mload(add(note, 0x60))) mstore(add(m, 0x40), mload(add(note, 0x80))) mstore(add(m, 0x60), mload(add(note, 0xa0))) noteHash := keccak256(m, 0x80) mstore(m, 0x0f1ea84c0ceb3ad2f38123d94a164612e1a0c14a694dc5bfa16bc86ea1f3eabd) // keccak256 hash of "AZTEC_NOTE_SIGNATURE(bytes32[4] note,uint256 challenge,address sender)" mstore(add(m, 0x20), noteHash) mstore(add(m, 0x40), challenge) mstore(add(m, 0x60), caller) mstore(add(m, 0x40), keccak256(m, 0x80)) mstore(add(m, 0x20), domainHashT) mstore(m, 0x1901) signatureMessage := keccak256(add(m, 0x1e), 0x42) } address owner = ecrecover(signatureMessage, uint8(signature[0]), signature[1], signature[2]); require(owner != address(0), "signature invalid"); require(noteRegistry[noteHash] == owner, "expected input note to exist in registry"); noteRegistry[noteHash] = 0; } /** * @dev Validate an output note from an AZTEC confidential transaction * If the note does not already exist in ```noteRegistry```, create it * @param note AZTEC confidential note to be created * @param owner The address of the note owner **/ function validateOutputNote(bytes32[6] note, address owner) internal { bytes32 noteHash; // Construct a keccak256 hash of the note coordinates. assembly { let m := mload(0x40) mstore(m, mload(add(note, 0x40))) mstore(add(m, 0x20), mload(add(note, 0x60))) mstore(add(m, 0x40), mload(add(note, 0x80))) mstore(add(m, 0x60), mload(add(note, 0xa0))) noteHash := keccak256(m, 0x80) } require(owner != address(0), "owner must be valid Ethereum address"); require(noteRegistry[noteHash] == 0, "expected output note to not exist in registry"); noteRegistry[noteHash] = owner; } /** * @dev Perform a confidential transaction. Takes ```m``` input notes and ```notes.length - m``` output notes. * ```notes, m, challenge``` constitute an AZTEC zero-knowledge proof that states the following: * The sum of the values of the input notes is equal to a the sum of the values of the output notes + a public commitment value ```kPublic``` * \sum_{i=0}^{m-1}k_i = \sum_{i=m}^{n-1}k_i + k_{public} (mod p) * notes[6][] contains value ```kPublic``` at notes[notes.length - 1][0]. * If ```kPublic``` is negative, this represents ```(GROUP_MODULUS - kPublic) * SCALING_FACTOR``` ERC20 tokens being converted into confidential note form. * If ```kPublic``` is positive, this represents ```kPublic * SCALING_FACTOR``` worth of AZTEC notes being converted into ERC20 form * @param notes defines AZTEC input notes and output notes. notes[0,...,m-1] = input notes. notes[m,...,notes.length-1] = output notes * @param m where notes[0,..., m - 1] = input notes. notes[m,...,notes.length - 1] = output notes * @param challenge AZTEC zero-knowledge proof challenge variable * @param inputSignatures array of ECDSA signatures, one for each input note * @param outputOwners addresses of owners, one for each output note * Unnamed param is metadata: if AZTEC notes are assigned to stealth addresses, metadata should contain the ephemeral keys required for note owner to identify their note */ function confidentialTransfer(bytes32[6][] notes, uint256 m, uint256 challenge, bytes32[3][] inputSignatures, address[] outputOwners, bytes) external { require(inputSignatures.length == m, "input signature length invalid"); require(inputSignatures.length + outputOwners.length == notes.length, "array length mismatch"); // validate AZTEC zero-knowledge proof require(AZTECInterface.validateJoinSplit(notes, m, challenge, setupPubKey), "proof not valid!"); // extract variable kPublic from proof uint256 kPublic = uint(notes[notes.length - 1][0]); require(kPublic < groupModulus, "invalid value of kPublic"); // iterate over the notes array and validate each input/output note for (uint256 i = 0; i < notes.length; i++) { // if i < m this is an input note if (i < m) { // call validateInputNote to check that the note exists and that we have a matching signature over the note. // pass domainHash in as a function parameter to prevent multiple sloads // this will remove the input notes from noteRegistry validateInputNote(notes[i], inputSignatures[i], challenge, domainHash); } else { // if i >= m this is an output note // validate that output notes, attached to the specified owners do not exist in noteRegistry. // if all checks pass, add notes into note registry validateOutputNote(notes[i], outputOwners[i - m]); } } if (kPublic > 0) { if (kPublic < groupModulusBoundary) { // if value < the group modulus boundary then this public value represents a conversion from confidential note form to public form // call token.transfer to send relevent tokens require(token.transfer(msg.sender, kPublic * scalingFactor), "token transfer to user failed!"); } else { // if value > group modulus boundary, this represents a commitment of a public value into confidential note form. // only proceed if the required transferFrom call from msg.sender to this contract succeeds require(token.transferFrom(msg.sender, this, (groupModulus - kPublic) * scalingFactor), "token transfer from user failed!"); } } // emit an event to mark this transaction. Can recover notes + metadata from input data emit ConfidentialTransfer(); } }
Perform a confidential transaction. Takes ```m``` input notes and ```notes.length - m``` output notes. ```notes, m, challenge``` constitute an AZTEC zero-knowledge proof that states the following: The sum of the values of the input notes is equal to a the sum of the values of the output notes + a public commitment value ```kPublic``` \sum_{i=0}^{m-1}k_i = \sum_{i=m}^{n-1}k_i + k_{public} (mod p) notes[6][] contains value ```kPublic``` at notes[notes.length - 1][0]. If ```kPublic``` is negative, this represents ```(GROUP_MODULUS - kPublic) SCALING_FACTOR``` ERC20 tokens being converted into confidential note form. If ```kPublic``` is positive, this represents ```kPublic SCALING_FACTOR``` worth of AZTEC notes being converted into ERC20 form notes defines AZTEC input notes and output notes. notes[0,...,m-1] = input notes. notes[m,...,notes.length-1] = output notes m where notes[0,..., m - 1] = input notes. notes[m,...,notes.length - 1] = output notes challenge AZTEC zero-knowledge proof challenge variable inputSignatures array of ECDSA signatures, one for each input note outputOwners addresses of owners, one for each output note Unnamed param is metadata: if AZTEC notes are assigned to stealth addresses, metadata should contain the ephemeral keys required for note owner to identify their note/ validate AZTEC zero-knowledge proof extract variable kPublic from proof iterate over the notes array and validate each input/output note if i < m this is an input note call validateInputNote to check that the note exists and that we have a matching signature over the note. pass domainHash in as a function parameter to prevent multiple sloads this will remove the input notes from noteRegistry if i >= m this is an output note validate that output notes, attached to the specified owners do not exist in noteRegistry. if all checks pass, add notes into note registry if value < the group modulus boundary then this public value represents a conversion from confidential note form to public form call token.transfer to send relevent tokens if value > group modulus boundary, this represents a commitment of a public value into confidential note form. only proceed if the required transferFrom call from msg.sender to this contract succeeds
function confidentialTransfer(bytes32[6][] notes, uint256 m, uint256 challenge, bytes32[3][] inputSignatures, address[] outputOwners, bytes) external { require(inputSignatures.length == m, "input signature length invalid"); require(inputSignatures.length + outputOwners.length == notes.length, "array length mismatch"); require(AZTECInterface.validateJoinSplit(notes, m, challenge, setupPubKey), "proof not valid!"); uint256 kPublic = uint(notes[notes.length - 1][0]); require(kPublic < groupModulus, "invalid value of kPublic"); for (uint256 i = 0; i < notes.length; i++) { if (i < m) { validateInputNote(notes[i], inputSignatures[i], challenge, domainHash); validateOutputNote(notes[i], outputOwners[i - m]); } } if (kPublic > 0) { if (kPublic < groupModulusBoundary) { require(token.transfer(msg.sender, kPublic * scalingFactor), "token transfer to user failed!"); require(token.transferFrom(msg.sender, this, (groupModulus - kPublic) * scalingFactor), "token transfer from user failed!"); } } }
7,236,031
// contracts/Vero.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "./IVero.sol"; import "./VeroStatuses.sol"; /// @title Smart contract for Virtual Equivalents of Real Objects, or VEROs for short /// @author Joe Cora /// @notice Supports all of the conditions in order to assure that this NFT can be confirmed /// to become a VERO. Find additional details at https://vero-nft.org. Also, supports pausing the smart contract /// for better security and easier contract migrations. /// @dev Leverages the OpenZeppelin library to implement a contract that contains all of the /// standard NFT (ERC-721) functions. Using some ERC-721 optional extension contracts to make /// a VERO more usable on the blockchain and to have token metadata stored off the blockchain. contract Vero is ERC721Enumerable, ERC721URIStorage, Pausable, IVero { // Tracks VERO status for all NFTs minted against this contract mapping(uint256 => VeroStatuses) private _veroStatuses; // Tracks uniqueness of VERO token URIs, which are stored off-chain string[] private _tokenUris; mapping(string => bool) private _tokenUriExists; // Define the VERO admin roles (who can only change the VERO status - not any NFT behavior) address private _veroAdminAddress; /// @notice Sets up the VERO admin roles that will only be able to modify the VERO status /// and not any attributes that affect this token to exist as an NFT constructor() ERC721("VERO", "VRO") { // The VERO admin address is the one that creates this contract _veroAdminAddress = msg.sender; } // VERO-specific events /////////////////////////////////////////////////////////////////////// /// @dev Emitted when new VERO admin address is set, excluding when the contract is created event VeroAdminChanged(address indexed previousAdmin, address indexed newAdmin); /// @dev Emitted when the VERO status of an NFT minted against this contract changes outside /// of the initial minting event VeroStatusChanged(address indexed _admin, uint256 indexed _tokenId, VeroStatuses previousStatus, VeroStatuses newStatus ); // VERO-specific modifiers and functions ////////////////////////////////////////////////////// /// @dev Access modifier to limit calling from the VERO admin address alone modifier onlyVeroAdmin() { require(msg.sender == _veroAdminAddress); _; } /// @notice Pauses the contract so no additional smart contract state changes can occur. Helps stop active exploits /// from continuing unimpeded and also helps facilitate smart contract migrations /// @dev Will throw an error if tried by an account outside of the VERO admin account or if the contract is already /// paused function pause() external onlyVeroAdmin override { _pause(); } /// @notice Unpauses the contract so smart contract state changes can occur. Unpausing returns things to normal /// @dev Will throw an error if tried by an account outside of the VERO admin account or if the contract is not /// paused function unpause() external onlyVeroAdmin override { _unpause(); } /// @notice Retrieves the VERO admin address for anyone to see which account is the admin /// @return tokenId for the newly minted NFT function getVeroAdmin() external view override returns (address) { return _veroAdminAddress; } /// @notice Changes the VERO admin address to a new address, which changes admin ownership. /// The VERO admin should only call this with a high level of intentionality and care. /// @dev Will throw errors on changes to the null address or this contract address. The /// existing VERO admin account is the only one that can call this method. Throws an error when contract is /// paused. Emits a "VeroAdminChanged" event upon changing the admin address. /// @param newAdmin The address for the account that will become the new admin function changeVeroAdmin(address newAdmin) external onlyVeroAdmin whenNotPaused override { require(newAdmin != address(0), "VERO: cannot change admin to null address"); require(newAdmin != address(this), "VERO: cannot change admin to this contract address"); require(newAdmin != msg.sender, "VERO: cannot change admin to current admin"); _veroAdminAddress = newAdmin; emit VeroAdminChanged(msg.sender, newAdmin); } /// @notice Creates an NFT with token metadata stored off-chain for sender, who should be the /// owner, and stores the VERO status as PENDING. This does not create a VERO as a VERO must /// be approved before it is classified as such. /// @dev Throws error on already used token URI or token ID overflow. Throws an error when paused. /// @param _tokenURI The token URI, stored off-chain, to use to mint the NFT /// @return tokenId for the newly minted NFT function createAsPending(string memory _tokenURI) external virtual whenNotPaused override returns (uint256) { require(msg.sender != address(0), "VERO: cannot mint against null address"); require(msg.sender != address(this), "VERO: cannot mint against this contract address"); uint256 newTokenId = _consumeTokenUri(_tokenURI); _safeMint(msg.sender, newTokenId); _setTokenURI(newTokenId, _tokenURI); _setDefaultVeroStatus(newTokenId); return newTokenId; } /// @notice Retrieves the VERO status for an NFT minted against the VERO smart contract /// @dev Throws error when token does not exist /// @param _tokenId The token upon which to set the default status /// @return VERO status for the NFT using VeroStatuses enum value function getVeroStatus(uint256 _tokenId) external view virtual override returns (VeroStatuses) { require(_exists(_tokenId), "VERO: operator query for nonexistent token"); return _getVeroStatus(_tokenId); } /// @notice Approves the VERO status for the token from the VERO admin address only. /// @dev Emits a "VeroStatusChanged" event upon changing the VERO status. Throws error /// when token does not exist. Throws an error when paused. /// @param _tokenId The token to approve as a VERO function approveAsVero(uint256 _tokenId) external virtual onlyVeroAdmin whenNotPaused override { require(_exists(_tokenId), "VERO: operator query for nonexistent token"); VeroStatuses currentStatus = _getVeroStatus(_tokenId); VeroStatuses newStatus = VeroStatuses.APPROVED; require(currentStatus != newStatus, "VERO: cannot approve an already approved VERO"); _setVeroStatus(_tokenId, newStatus); emit VeroStatusChanged(msg.sender, _tokenId, currentStatus, newStatus); } /// @notice Rejects the VERO status for the token from the VERO admin address only. Must /// be in a PENDING status to reject /// @dev Emits a "VeroStatusChanged" event upon changing the VERO status. Throws error /// when token does not exist. Throws an error when paused. /// @param _tokenId The token to reject as a VERO function rejectAsVero(uint256 _tokenId) external virtual onlyVeroAdmin whenNotPaused override { require(_exists(_tokenId), "VERO: operator query for nonexistent token"); VeroStatuses currentStatus = _getVeroStatus(_tokenId); VeroStatuses newStatus = VeroStatuses.REJECTED; require(currentStatus == VeroStatuses.PENDING, "VERO: cannot reject a VERO that is not in a PENDING status" ); _setVeroStatus(_tokenId, newStatus); emit VeroStatusChanged(msg.sender, _tokenId, currentStatus, newStatus); } /// @notice Revokes the VERO status for the token from the VERO admin address only. Must /// be in an APPROVED status to revoke /// @dev Emits a "VeroStatusChanged" event upon changing the VERO status. Throws error /// when token does not exist. Throws an error when paused. /// @param _tokenId The token to revoke as a VERO function revokeAsVero(uint256 _tokenId) external virtual onlyVeroAdmin whenNotPaused override { require(_exists(_tokenId), "VERO: operator query for nonexistent token"); VeroStatuses currentStatus = _getVeroStatus(_tokenId); VeroStatuses newStatus = VeroStatuses.REVOKED; require(currentStatus == VeroStatuses.APPROVED, "VERO: cannot revoke a VERO that is not in an APPROVED status" ); _setVeroStatus(_tokenId, newStatus); emit VeroStatusChanged(msg.sender, _tokenId, currentStatus, newStatus); } /// @dev Adds the token URI to the list of used token URIs, if unused, so it cannot be reused. Throws an error /// if the tokenId is not greater than 0 /// @param @param _tokenURI The token URI to not allow for subsequent minting upon /// @return tokenId for the token URI function _consumeTokenUri(string memory _tokenUri) internal virtual returns (uint256) { require(!_tokenUriExists[_tokenUri], "VERO: cannot mint with an already used token URI"); _tokenUris.push(_tokenUri); uint256 _tokenId = _tokenUris.length; require(_tokenId > 0); _tokenUriExists[_tokenUri] = true; return _tokenId; } /// @dev Sets the default VERO status for the NFT, which is PENDING /// @param _tokenId The token upon which to set the default status function _setDefaultVeroStatus(uint256 _tokenId) internal virtual { _veroStatuses[_tokenId] = VeroStatuses.PENDING; } /// @dev Internal function to handle retrieving VERO status /// @param _tokenId The token upon which to set the default status /// @return VERO status for the NFT using VeroStatuses enum value function _getVeroStatus(uint256 _tokenId) internal view virtual returns (VeroStatuses) { return _veroStatuses[_tokenId]; } /// @dev Sets the VERO status for the NFT, which can only be run by the VERO admin address /// @param _tokenId The token upon which to set the default status /// @param newStatus The new status to be assigned to the token function _setVeroStatus(uint256 _tokenId, VeroStatuses newStatus) internal virtual onlyVeroAdmin { _veroStatuses[_tokenId] = newStatus; } // Overridden functions from base contracts (functions clashes) /////////////////////////////// /// @notice Checks if the incoming interface ID is supported by this contract. The contract /// supports standard NFT (ERC-721) interface and all of the specifications that that contract /// is extended from. Also supports the VERO interface. /// @dev Calls the ERC721Enumerable base method as that method extends from ERC721 and calls /// that base method, too. /// @param interfaceId ID for the interface to check for contract support upon /// @return Boolean for whether the contract supports the incoming interface function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return interfaceId == type(IVero).interfaceId || ERC721Enumerable.supportsInterface(interfaceId); } /// @notice Retrieves the token URI, which is stored off-chain, for the specified token ID /// @dev Calls the ERC721URIStorage base method as that method extends from ERC721 and calls /// that base method, too. /// @param tokenId ID for the NFT created against this contract /// @return URI for the token function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return ERC721URIStorage.tokenURI(tokenId); } /// @dev Calls the ERC721Enumerable base method as that method extends from ERC721 and calls /// that base method, too. Throws an error when paused. /// @param from Blockchain address for the account transferring the NFT /// @param to Blockchain address for the account to which the NFT is being transferred /// @param tokenId ID for the NFT created against this contract function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual whenNotPaused override(ERC721, ERC721Enumerable) { ERC721Enumerable._beforeTokenTransfer(from, to, tokenId); } /// @dev Calls the ERC721URIStorage base method as that method extends from ERC721 and calls /// that base method, too. Throws an error when paused. /// @param tokenId ID for the NFT created against this contract function _burn(uint256 tokenId) internal virtual whenNotPaused override(ERC721, ERC721URIStorage) { ERC721URIStorage._burn(tokenId); } // Overridden functions from base contracts (add pausability) ///////////////////////////////// /// @dev Calls the ERC721 base method. Throws an error when paused. /// @param operator Address to allow or disallow approval for on the caller's tokens /// @param approved Whether to approve or disallow approval function setApprovalForAll(address operator, bool approved) public virtual whenNotPaused override { ERC721.setApprovalForAll(operator, approved); } /// @dev Calls the ERC721 base method. Throws an error when paused. /// @param to Address to approve as token surrogate /// @param tokenId Token to apply approval to function _approve(address to, uint256 tokenId) internal virtual whenNotPaused override { ERC721._approve(to, tokenId); } }
Calls the ERC721Enumerable base method as that method extends from ERC721 and calls that base method, too. Throws an error when paused. from Blockchain address for the account transferring the NFT to Blockchain address for the account to which the NFT is being transferred tokenId ID for the NFT created against this contract
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual whenNotPaused override(ERC721, ERC721Enumerable) { ERC721Enumerable._beforeTokenTransfer(from, to, tokenId); }
2,512,148
./full_match/4/0xB238314f8918A1bE89E082b97002f5A9BC6610EE/sources/SKETCH.sol
Start the public sale/
function startPublicSale() public onlyOwner { hasPublicSaleStarted = true; }
680,351
./partial_match/42/0xC31518D4fbA20E3618F6e7B24D1Bada43837Ed45/sources/GebProxyDebtAuctionActions.sol
Allow/disallow a usr address to quit to the sender handler manager address - Safe Manager usr address - usr address uint ok - 1 for allowed
function allowHandler( address manager, address usr, uint ok ) external { ManagerLike(manager).allowHandler(usr, ok); }
3,338,798
./partial_match/4/0xc4Ed932865F52B0458f0817A522eB69A0F304e2b/sources/PriceBettingT1S.sol
console.log("[sc] ----== handleWinning");console.log("[sc] handleWinning",gain, gainAndPrincipal); Pool loses 1, the governance gets 0.12token.safeTransfer(bet.addr, gainAndPrincipal);amount1.88 as total winning amount, and 0 for losing the bet amount, amount1 as tie returned to the better
function handleWinning(uint256 period, uint256 betIdx, uint256 gain, uint256 gainAndPrincipal) internal { Bet memory bet = getBet(period, betIdx); poolBalance = poolBalance.sub(bet.amount); amt = gain; amt = gainAndPrincipal; } updateBetterUnclaimed(true, amt, bet.addr); setBetResult(period, betIdx, gainAndPrincipal); Win(bet.addr, block.timestamp, amt, betIdx, bet.period);
8,748,028
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol'; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "./interfaces/IDPexRouter.sol"; import "./interfaces/IFeeAggregator.sol"; import "./interfaces/IPSI.sol"; import "./abstracts/PSIGovernable.sol"; contract FeeAggregator is IFeeAggregator, Initializable, ContextUpgradeable, PSIGovernable { using SafeERC20Upgradeable for IERC20Upgradeable; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; //== Variables == EnumerableSetUpgradeable.AddressSet private _feeTokens; // all the token where a fee is deducted from on swap /** * @notice psi token contract */ address public psi; /** * @notice base token contract (weth/wbnb) */ address public baseToken; /** * @notice percentage which get deducted from a swap (1 = 0.1%) */ uint256 public dpexFee; /** * @notice token fees gathered in the current period */ mapping(address => uint256) public tokensGathered; uint256 private constant MAX_INT = 2**256 - 1; //== CONSTRUCTOR == /** * @dev Initializes the contract setting the deployer as the initial Governor. */ function initialize(address _gov_contract, address _baseToken, address _psi) public initializer { __Context_init(); super.initialize(_gov_contract); dpexFee = 1; psi = _psi; baseToken = _baseToken; } //== MODIFIERS == modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'FeeAggregator: EXPIRED'); _; } //== VIEW == /** * @notice return all the tokens where a fee is deducted from on swap */ function feeTokens() external override view returns (address[] memory) { address[] memory tokens = new address[](_feeTokens.length()); for(uint256 idx = 0; idx < _feeTokens.length(); idx++) { tokens[idx] = _feeTokens.at(idx); } return tokens; } /** * @notice checks if the token is a token where a fee is deducted from on swap * @param token fee token to check */ function isFeeToken(address token) public override view returns (bool) { return _feeTokens.contains(token); } /** * @notice returns the fee for the amount given * @param amount amount to calculate the fee for */ function calculateFee(uint256 amount) public override view returns (uint256 fee, uint256 amountLeft) { amountLeft = ((amount * 1000) - (amount * dpexFee)) / 1000; fee = amount - amountLeft; } /** * @notice returns the fee for the amount given, but only if the token is in the feetokens list * @param token token to check if it exists in the feetokens list * @param amount amount to calculate the fee for */ function calculateFee(address token, uint256 amount) external override view returns (uint256 fee, uint256 amountLeft) { if (!_feeTokens.contains(token)) { return (0, amount); } return calculateFee(amount); } //== SET INTERNAL VARIABLES== /** * @notice add a token to deduct a fee for on swap * @param token fee token to add */ function addFeeToken(address token) public override onlyGovernor { require(!_feeTokens.contains(token), "FeeAggregator: ALREADY_FEE_TOKEN"); _feeTokens.add(token); approveFeeToken(token); } /** * @notice add fee tokens to deduct a fee for on swap * @param tokens fee tokens to add */ function addFeeTokens(address[] calldata tokens) external override onlyGovernor { for(uint256 idx = 0; idx < tokens.length; idx++) { addFeeToken(tokens[idx]); } } /** * @notice approve a single fee token on the router * @param token fee token to approve */ function approveFeeToken(address token) public override onlyGovernor { IERC20Upgradeable(token).approve(router(), MAX_INT); } /** * @notice approve all fee tokens on the router */ function approveFeeTokens() external override onlyGovernor { for(uint256 idx = 0; idx < _feeTokens.length(); idx++) { address token = _feeTokens.at(idx); approveFeeToken(token); } } /** * @notice remove a token to deduct a fee for on swap * @param token fee token to add */ function removeFeeToken(address token) external override onlyGovernor { require(_feeTokens.contains(token), "FeeAggregator: NO_FEE_TOKEN"); _feeTokens.remove(token); } /** * @notice set the percentage which get deducted from a swap (1 = 0.1%) * @param fee percentage to set as fee */ function setDPexFee(uint256 fee) external override onlyGovernor { require(fee >= 0 && fee <= 200, "FeeAggregator: FEE_MIN_0_MAX_20"); dpexFee = fee; } /** * @notice set a new PSI address * @param _psi psi token address */ function setPSIAddress(address _psi) external override onlyGovernor { psi = _psi; } /** * @notice Adds a fee to the tokensGathered list. For example from the DPEX router * @param token fee token to check * @param fee fee to add to the tokensGathered list */ function addTokenFee(address token, uint256 fee) external override { require (_feeTokens.contains(token), "Token is not a feeToken"); tokensGathered[token] += fee; } /** * @notice Adds multiple fees to the tokensGathered list. For example from the DPEX router * @param tokens fee tokens to check * @param fees fees to add to the tokensGathered list */ function addTokenFees(address[] memory tokens, uint256[] memory fees) external override { require (tokens.length == fees.length, "Token is not a feeToken"); for(uint256 idx = 0; idx < tokens.length; idx++) { require (_feeTokens.contains(tokens[idx]), "Token is not a feeToken"); tokensGathered[tokens[idx]] += fees[idx]; } } /** * @notice sells all fees for PSI and reflects them over the PSI holders */ function reflectFees(uint256 deadline) external override onlyGovernor ensure(deadline) { uint256 psiBalanceBefore = IERC20Upgradeable(psi).balanceOf(address(this)); _sellFeesToPSI(); uint256 psiFeeBalance = IERC20Upgradeable(psi).balanceOf(address(this)) - psiBalanceBefore; if (tokensGathered[psi] > 0) { psiFeeBalance += tokensGathered[psi]; tokensGathered[psi] = 0; } IPSI(psi).reflect(psiFeeBalance); } /** * @notice sells a single fee for PSI and reflects them over the PSI holders */ function reflectFee(address token, uint256 deadline) external override onlyGovernor ensure(deadline) { require(_feeTokens.contains(token), "FeeAggregator: NO_FEE_TOKEN"); uint256 psiBalanceBefore = IERC20Upgradeable(psi).balanceOf(address(this)); uint256 psiFeeBalance; if (token == psi) { psiFeeBalance = tokensGathered[psi]; require(psiFeeBalance > 0, "FeeAggregator: NO_FEE_TOKEN_BALANCE"); } else { _sellFeeToPSI(token); psiFeeBalance = IERC20Upgradeable(psi).balanceOf(address(this)) - psiBalanceBefore; } IPSI(psi).reflect(psiFeeBalance); } function _sellFeesToPSI() internal { for(uint256 idx = 0; idx < _feeTokens.length(); idx++) { address token = _feeTokens.at(idx); uint256 tokenBalance = IERC20Upgradeable(token).balanceOf(address(this)); if (token != baseToken && token != psi && tokenBalance > 0) { tokensGathered[token] = 0; address[] memory path = new address[](2); path[0] = token; path[1] = baseToken; IDPexRouter(router()).swapAggregatorToken(tokenBalance, path, address(this)); } } _sellBaseTokenToPSI(); } function _sellFeeToPSI(address token) internal { uint256 tokenBalance = IERC20Upgradeable(token).balanceOf(address(this)); require(tokenBalance > 0, "FeeAggregator: NO_FEE_TOKEN_BALANCE"); if (token != baseToken && token != psi && tokenBalance > 0) { tokensGathered[token] = 0; address[] memory path = new address[](3); path[0] = token; path[1] = baseToken; path[2] = psi; IDPexRouter(router()).swapAggregatorToken(tokenBalance, path, address(this)); } else if(token == baseToken) { _sellBaseTokenToPSI(); } } function _sellBaseTokenToPSI() internal { uint256 balance = IERC20Upgradeable(baseToken).balanceOf(address(this)); if (balance <= 0) return; tokensGathered[baseToken] = 0; address[] memory path = new address[](2); path[0] = baseToken; path[1] = psi; IDPexRouter(router()).swapAggregatorToken(balance, path, address(this)); } }
set a new PSI address _psi psi token address/
function setPSIAddress(address _psi) external override onlyGovernor { psi = _psi; }
5,444,685
pragma solidity >=0.4.24 <0.6.0; import "zos-lib/contracts/Initializable.sol"; contract LinkedList is Initializable{ event EntryAdded(bytes32 head, string data, bytes32 next); //Struct will be our Node struct Node { bytes32 next; string data; } //Mappping will hold nodes mapping (bytes32 => Node) public nodes; //Length of LinkedList (initialize with constructor/initalizer) uint public length; //Head of list; bytes32 public head; //Name of LinkedList (the purpose for the list) string public listName; function initialize(string memory _listName) initializer public { require(bytes(_listName).length >= 0); length = 0; listName = _listName; } function addNode(string memory _data) public returns (bool){ Node memory node = Node(head, _data); bytes32 id = keccak256(abi.encodePacked(node.data, length, now)); nodes[id] = node; head = id; length = length+1; emit EntryAdded(head, node.data, node.next); } //popNode function popHead() public returns (bool) { require(length > 0, "error...head is empty"); //hold this to delete it bytes32 newHead = nodes[head].next; //delete it delete nodes[head]; head = newHead; length = length-1; } //Contract interface function getNodeExternal(bytes32 _node) external view returns (bytes32, string memory){ return (nodes[_node].next, nodes[_node].data); } }
popNodehold this to delete itdelete it
function popHead() public returns (bool) { require(length > 0, "error...head is empty"); bytes32 newHead = nodes[head].next; delete nodes[head]; head = newHead; length = length-1; }
15,848,956
pragma solidity 0.5.15; contract IAugur { function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING } contract IOwnable { function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING } contract ITyped { function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING } library SafeMathUint256 { function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); return a - b; } function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a <= b) { return a; } else { return b; } } function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a >= b) { return a; } else { return b; } } function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING if (y > 3) { uint256 x = (y + 1) / 2; z = y; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING return 0; } function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING return a % b == 0; } // Float [fixed point] Operations function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, b), base); } function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, base), b); } } interface IERC1155 { event TRANSFERSINGLE49( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TRANSFERBATCH882( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event APPROVALFORALL731( //inject NONSTANDARD NAMING address indexed owner, address indexed operator, bool approved ); event URI998( //inject NONSTANDARD NAMING string value, uint256 indexed id ); function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING address from, address to, uint256 id, uint256 value, bytes calldata data ) external; function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFBATCH918( //inject NONSTANDARD NAMING address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } contract IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING // solhint-disable-next-line no-simple-event-func-name event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ICash is IERC20 { } contract ERC20 is IERC20 { using SafeMathUint256 for uint256; uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING uint256 public totalSupply; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_account]; } function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(msg.sender, _recipient, _amount); return true; } function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowances[_owner][_spender]; } function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, _amount); return true; } function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(_sender, _recipient, _amount); _APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount)); return true; } function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue)); return true; } function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue)); return true; } function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); balances[_sender] = balances[_sender].SUB692(_amount); balances[_recipient] = balances[_recipient].ADD571(_amount); emit TRANSFER723(_sender, _recipient, _amount); ONTOKENTRANSFER292(_sender, _recipient, _amount); } function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.ADD571(_amount); balances[_account] = balances[_account].ADD571(_amount); emit TRANSFER723(address(0), _account, _amount); } function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: burn from the zero address"); balances[_account] = balances[_account].SUB692(_amount); totalSupply = totalSupply.SUB692(_amount); emit TRANSFER723(_account, address(0), _amount); } function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING 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 APPROVAL665(_owner, _spender, _amount); } function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING _BURN356(_account, _amount); _APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount)); } // Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING } contract VariableSupplyToken is ERC20 { using SafeMathUint256 for uint256; function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _MINT880(_target, _amount); ONMINT315(_target, _amount); return true; } function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _BURN356(_target, _amount); ONBURN653(_target, _amount); return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING } } contract IAffiliateValidator { function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING } contract IDisputeWindow is ITyped, IERC20 { function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING } contract IReportingParticipant { function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING } contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 { function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING } contract IInitialReporter is IReportingParticipant, IOwnable { function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING } contract IReputationToken is IERC20 { function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING } contract IShareToken is ITyped, IERC1155 { function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING } contract IUniverse { function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING function FORK341() public returns (bool); //inject NONSTANDARD NAMING function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING } contract IV2ReputationToken is IReputationToken { function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING } library Reporting { uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING } contract IAugurTrading { function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING } contract IOrders { function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IMarket market; IAugur augur; IAugurTrading augurTrading; IShareToken shareToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken")); return Data({ market: _market, augur: _augur, augurTrading: _augurTrading, shareToken: _shareToken, cash: ICash(_augur.LOOKUP594("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING if (_orderData.id == bytes32(0)) { bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed)); } function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING GETORDERID157(_orderData, _orders); uint256[] memory _uints = new uint256[](5); _uints[0] = _orderData.amount; _uints[1] = _orderData.price; _uints[2] = _orderData.outcome; _uints[3] = _orderData.moneyEscrowed; _uints[4] = _orderData.sharesEscrowed; bytes32[] memory _bytes32s = new bytes32[](4); _bytes32s[0] = _orderData.betterOrderId; _bytes32s[1] = _orderData.worseOrderId; _bytes32s[2] = _tradeGroupId; _bytes32s[3] = _orderData.id; return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator); } } interface IUniswapV2Pair { event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP992( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM81(address to) external; //inject NONSTANDARD NAMING function SYNC86() external; //inject NONSTANDARD NAMING function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING } contract IRepSymbol { function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING } contract ReputationToken is VariableSupplyToken, IV2ReputationToken { using SafeMathUint256 for uint256; string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING IUniverse internal universe; IUniverse public parentUniverse; uint256 internal totalMigrated; IERC20 public legacyRepToken; IAugur public augur; address public warpSync; constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public { augur = _augur; universe = _universe; parentUniverse = _parentUniverse; warpSync = _augur.LOOKUP594("WarpSync"); legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken")); require(warpSync != address(0)); require(legacyRepToken != IERC20(0)); } function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe)); } function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(_attotokens > 0); IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators); IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35(); BURN234(msg.sender, _attotokens); _destination.MIGRATEIN692(msg.sender, _attotokens); return true; } function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING IUniverse _parentUniverse = parentUniverse; require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35()); require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510()); MINT146(_reporter, _attotokens); totalMigrated += _attotokens; // Update the fork tentative winner and finalize if we can if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) { _parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230()); } return true; } function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender); require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant)); // simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute uint256 _bonus = _amountMigrated.MUL760(2) / 5; MINT146(address(_reportingParticipant), _bonus); return true; } function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING require(warpSync == msg.sender); MINT146(_target, _amountToMint); universe.UPDATEFORKVALUES73(); return true; } function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); BURN234(msg.sender, _amountToBurn); return true; } function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(IUniverse(msg.sender) == universe); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING IUniverse _universe = _shadyReputationToken.GETUNIVERSE719(); require(universe.ISPARENTOF319(_universe)); require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken); } function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING return universe; } function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING return totalMigrated; } function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING return legacyRepToken; } function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _totalSupply = totalSupply; if (parentUniverse == IUniverse(0)) { return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0))); } else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) { return _totalSupply; } else { return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552(); } } function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]); } function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]); } function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]); } function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING require(parentUniverse == IUniverse(0)); uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender); require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance)); MINT146(msg.sender, _legacyBalance); return true; } }
inject NONSTANDARD NAMING
function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) {
2,554,117
./full_match/1/0x83487B13e7B68536047B10A79b37FBe74eE8B394/sources/contracts/DirectTokenV2.sol
Returns to normal state. Requirements: - The contract must be paused./
function unpause() public payable whenPaused onlyOwner { require(isPausable(), "Contract is not pausable"); _paused = false; emit Unpaused(msg.sender); }
17,146,886
/** *Submitted for verification at Etherscan.io on 2022-01-18 */ pragma solidity 0.6.12; // SPDX-License-Identifier: GPL-3.0-only /** * @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; } } interface IStafiStorage { // Getters function getAddress(bytes32 _key) external view returns (address); function getUint(bytes32 _key) external view returns (uint); function getString(bytes32 _key) external view returns (string memory); function getBytes(bytes32 _key) external view returns (bytes memory); function getBool(bytes32 _key) external view returns (bool); function getInt(bytes32 _key) external view returns (int); function getBytes32(bytes32 _key) external view returns (bytes32); // Setters function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string calldata _value) external; function setBytes(bytes32 _key, bytes calldata _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // Deleters function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; } abstract contract StafiBase { // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained IStafiStorage stafiStorage = IStafiStorage(0); /** * @dev Throws if called by any sender that doesn't match a network contract */ modifier onlyLatestNetworkContract() { require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract"); _; } /** * @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract */ modifier onlyLatestContract(string memory _contractName, address _contractAddress) { require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract"); _; } /** * @dev Throws if called by any sender that isn't a trusted node */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.trusted", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered staking pool */ modifier onlyRegisteredStakingPool(address _stakingPoolAddress) { require(getBool(keccak256(abi.encodePacked("stakingpool.exists", _stakingPoolAddress))), "Invalid staking pool"); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(roleHas("owner", msg.sender), "Account is not the owner"); _; } /** * @dev Modifier to scope access to admins */ modifier onlyAdmin() { require(roleHas("admin", msg.sender), "Account is not an admin"); _; } /** * @dev Modifier to scope access to admins */ modifier onlySuperUser() { require(roleHas("owner", msg.sender) || roleHas("admin", msg.sender), "Account is not a super user"); _; } /** * @dev Reverts if the address doesn't have this role */ modifier onlyRole(string memory _role) { require(roleHas(_role, msg.sender), "Account does not match the specified role"); _; } /// @dev Set the main Storage address constructor(address _stafiStorageAddress) public { // Update the contract address stafiStorage = IStafiStorage(_stafiStorageAddress); } /// @dev Get the address of a network contract by name function getContractAddress(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Check it require(contractAddress != address(0x0), "Contract not found"); // Return return contractAddress; } /// @dev Get the name of a network contract by address function getContractName(address _contractAddress) internal view returns (string memory) { // Get the contract name string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress))); // Check it require(keccak256(abi.encodePacked(contractName)) != keccak256(abi.encodePacked("")), "Contract not found"); // Return return contractName; } /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return stafiStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint256) { return stafiStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return stafiStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return stafiStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return stafiStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int256) { return stafiStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return stafiStorage.getBytes32(_key); } function getAddressS(string memory _key) internal view returns (address) { return stafiStorage.getAddress(keccak256(abi.encodePacked(_key))); } function getUintS(string memory _key) internal view returns (uint256) { return stafiStorage.getUint(keccak256(abi.encodePacked(_key))); } function getStringS(string memory _key) internal view returns (string memory) { return stafiStorage.getString(keccak256(abi.encodePacked(_key))); } function getBytesS(string memory _key) internal view returns (bytes memory) { return stafiStorage.getBytes(keccak256(abi.encodePacked(_key))); } function getBoolS(string memory _key) internal view returns (bool) { return stafiStorage.getBool(keccak256(abi.encodePacked(_key))); } function getIntS(string memory _key) internal view returns (int256) { return stafiStorage.getInt(keccak256(abi.encodePacked(_key))); } function getBytes32S(string memory _key) internal view returns (bytes32) { return stafiStorage.getBytes32(keccak256(abi.encodePacked(_key))); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { stafiStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint256 _value) internal { stafiStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { stafiStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { stafiStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { stafiStorage.setBool(_key, _value); } function setInt(bytes32 _key, int256 _value) internal { stafiStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { stafiStorage.setBytes32(_key, _value); } function setAddressS(string memory _key, address _value) internal { stafiStorage.setAddress(keccak256(abi.encodePacked(_key)), _value); } function setUintS(string memory _key, uint256 _value) internal { stafiStorage.setUint(keccak256(abi.encodePacked(_key)), _value); } function setStringS(string memory _key, string memory _value) internal { stafiStorage.setString(keccak256(abi.encodePacked(_key)), _value); } function setBytesS(string memory _key, bytes memory _value) internal { stafiStorage.setBytes(keccak256(abi.encodePacked(_key)), _value); } function setBoolS(string memory _key, bool _value) internal { stafiStorage.setBool(keccak256(abi.encodePacked(_key)), _value); } function setIntS(string memory _key, int256 _value) internal { stafiStorage.setInt(keccak256(abi.encodePacked(_key)), _value); } function setBytes32S(string memory _key, bytes32 _value) internal { stafiStorage.setBytes32(keccak256(abi.encodePacked(_key)), _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { stafiStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { stafiStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { stafiStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { stafiStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { stafiStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { stafiStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { stafiStorage.deleteBytes32(_key); } function deleteAddressS(string memory _key) internal { stafiStorage.deleteAddress(keccak256(abi.encodePacked(_key))); } function deleteUintS(string memory _key) internal { stafiStorage.deleteUint(keccak256(abi.encodePacked(_key))); } function deleteStringS(string memory _key) internal { stafiStorage.deleteString(keccak256(abi.encodePacked(_key))); } function deleteBytesS(string memory _key) internal { stafiStorage.deleteBytes(keccak256(abi.encodePacked(_key))); } function deleteBoolS(string memory _key) internal { stafiStorage.deleteBool(keccak256(abi.encodePacked(_key))); } function deleteIntS(string memory _key) internal { stafiStorage.deleteInt(keccak256(abi.encodePacked(_key))); } function deleteBytes32S(string memory _key) internal { stafiStorage.deleteBytes32(keccak256(abi.encodePacked(_key))); } /** * @dev Check if an address has this role */ function roleHas(string memory _role, address _address) internal view returns (bool) { return getBool(keccak256(abi.encodePacked("access.role", _role, _address))); } } interface IStafiEther { function balanceOf(address _contractAddress) external view returns (uint256); function depositEther() external payable; function withdrawEther(uint256 _amount) external; } interface IStafiEtherWithdrawer { function receiveEtherWithdrawal() external payable; } // ETH are stored here to prevent contract upgrades from affecting balances // The contract must not be upgraded contract StafiEther is StafiBase, IStafiEther { // Libs using SafeMath for uint256; // Contract balances mapping(bytes32 => uint256) balances; // Events event EtherDeposited(bytes32 indexed by, uint256 amount, uint256 time); event EtherWithdrawn(bytes32 indexed by, uint256 amount, uint256 time); // Construct constructor(address _stafiStorageAddress) StafiBase(_stafiStorageAddress) public { version = 1; } // Get a contract's ETH balance by address function balanceOf(address _contractAddress) override public view returns (uint256) { return balances[keccak256(abi.encodePacked(getContractName(_contractAddress)))]; } // Accept an ETH deposit from a network contract function depositEther() override external payable onlyLatestNetworkContract { // Get contract key bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender))); // Update contract balance balances[contractKey] = balances[contractKey].add(msg.value); // Emit ether deposited event emit EtherDeposited(contractKey, msg.value, now); } // Withdraw an amount of ETH to a network contract function withdrawEther(uint256 _amount) override external onlyLatestNetworkContract { // Get contract key bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender))); // Check and update contract balance require(balances[contractKey] >= _amount, "Insufficient contract ETH balance"); balances[contractKey] = balances[contractKey].sub(_amount); // Withdraw IStafiEtherWithdrawer withdrawer = IStafiEtherWithdrawer(msg.sender); withdrawer.receiveEtherWithdrawal{value: _amount}(); // Emit ether withdrawn event emit EtherWithdrawn(contractKey, _amount, now); } }
Storage set methods
function setAddress(bytes32 _key, address _value) internal { stafiStorage.setAddress(_key, _value); }
2,006,599
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; /******************************************************************************\ * Custom implementation of the StakingRewards contract by Synthetix. * * https://docs.synthetix.io/contracts/source/contracts/stakingrewards * https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol /******************************************************************************/ import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/ILandWorks.sol"; import "./interfaces/IDecentralandEstateRegistry.sol"; contract LandWorksDecentralandStaking is ERC721Holder, ReentrancyGuard, Ownable, Pausable { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; ILandWorks public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 public totalSupply; mapping(address => uint256) public balances; mapping(uint256 => address) public stakedAssets; // metaverseId as per LandWorks protocol uint256 public metaverseId; address public landRegistry; IDecentralandEstateRegistry public estateRegistry; mapping(uint256 => uint256) public stakedAssetSizes; /* ========== CONSTRUCTOR ========== */ constructor( address _stakingToken, address _rewardsToken, uint256 _rewardsDuration, uint256 _metaverseId, address _landRegistry, address _estateRegistry ) { stakingToken = ILandWorks(_stakingToken); rewardsToken = IERC20(_rewardsToken); rewardsDuration = _rewardsDuration; metaverseId = _metaverseId; landRegistry = _landRegistry; estateRegistry = IDecentralandEstateRegistry(_estateRegistry); } /* ========== VIEWS ========== */ function lastTimeRewardApplicable() public view returns (uint256) { return block.timestamp < periodFinish ? block.timestamp : periodFinish; } function rewardPerToken() public view returns (uint256) { if (totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + (((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18) / totalSupply); } function earned(address account) public view returns (uint256) { return ((balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account])) / 1e18) + rewards[account]; } function getRewardForDuration() external view returns (uint256) { return rewardRate * rewardsDuration; } /// @notice Computes the represented amount to be staked, based on the LandWorks NFT /// @param tokenId The tokenId of the LandWorks NFT function computeAmount(uint256 tokenId) public view returns (uint256) { // Get the asset struct from Landworks ILandWorks.Asset memory landworksAsset = stakingToken.assetAt(tokenId); require(landworksAsset.metaverseId == metaverseId, "Staking: Invalid metaverseId"); require(landworksAsset.metaverseRegistry == landRegistry || landworksAsset.metaverseRegistry == address(estateRegistry), "Staking: Invalid metaverseRegistry"); // If the asset is LAND, amount is 1 uint256 computedAmount = 1; // If the asset is ESTATE, query the number of LAND's that it represents if (landworksAsset.metaverseRegistry == address(estateRegistry)) { computedAmount = estateRegistry.getEstateSize( landworksAsset.metaverseAssetId ); } return computedAmount; } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Stakes user's LandWorks NFTs /// @param tokenIds The tokenIds of the LandWorks NFTs which will be staked function stake(uint256[] memory tokenIds) external nonReentrant whenNotPaused updateReward(msg.sender) { require(tokenIds.length != 0, "Staking: No tokenIds provided"); uint256 amount; for (uint256 i = 0; i < tokenIds.length; i += 1) { // Transfer user's LandWorks NFTs to the staking contract stakingToken.safeTransferFrom(msg.sender, address(this), tokenIds[i]); // Change the consumer of the LandWorks NFT to be the person who staked it stakingToken.changeConsumer(msg.sender, tokenIds[i]); // Compute the amount/weight of the tokenId uint256 computedAmount = computeAmount(tokenIds[i]); // Increment the amount which will be staked amount += computedAmount; // Save the size, to be used on withdraw stakedAssetSizes[tokenIds[i]] = computedAmount; // Save who is the staker/depositor of the token stakedAssets[tokenIds[i]] = msg.sender; } _stake(amount); emit Staked(msg.sender, amount, tokenIds); } /// @notice Withdraws staked user's LandWorks NFTs /// @param tokenIds The tokenIds of the LandWorks NFT which will be withdrawn function withdraw(uint256[] memory tokenIds) public nonReentrant updateReward(msg.sender) { require(tokenIds.length != 0, "Staking: No tokenIds provided"); uint256 amount; for (uint256 i = 0; i < tokenIds.length; i += 1) { // Check if the user who withdraws is the owner require( stakedAssets[tokenIds[i]] == msg.sender, "Staking: Not the staker of the token" ); // Transfer LandWorks NFTs back to the owner stakingToken.safeTransferFrom(address(this), msg.sender, tokenIds[i]); amount += stakedAssetSizes[tokenIds[i]]; // Cleanup stakedAssetSizes for the current tokenId stakedAssetSizes[tokenIds[i]] = 0; // Cleanup stakedAssets for the current tokenId stakedAssets[tokenIds[i]] = address(0); } _withdraw(amount); emit Withdrawn(msg.sender, amount, tokenIds); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit(uint256[] memory tokenIds) external { withdraw(tokenIds); getReward(); } function _stake(uint256 _amount) internal { totalSupply += _amount; balances[msg.sender] += _amount; } function _withdraw(uint256 _amount) internal { totalSupply -= _amount; balances[msg.sender] -= _amount; } /* ========== RESTRICTED FUNCTIONS ========== */ /// @notice Calculates and sets the reward rate /// @param reward The amount of the reward which will be distributed during the entire period function notifyRewardAmount(uint256 reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward / rewardsDuration; } else { uint256 remaining = periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward + leftover) / rewardsDuration; } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance / rewardsDuration, "Staking: Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp + rewardsDuration; emit RewardAdded(reward); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Staking: Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount, uint256[] tokenIds); event Withdrawn(address indexed user, uint256 amount, uint256[] tokenIds); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./IERC721Consumable.sol"; interface ILandWorks is IERC721Consumable { enum AssetStatus { Listed, Delisted } struct Asset { uint256 metaverseId; address metaverseRegistry; uint256 metaverseAssetId; address paymentToken; uint256 minPeriod; uint256 maxPeriod; uint256 maxFutureTime; uint256 pricePerSecond; uint256 totalRents; AssetStatus status; } /// @notice Gets all asset data for a specific asset /// @param _assetId The target asset function assetAt(uint256 _assetId) external view returns (Asset memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IDecentralandEstateRegistry { /** * @notice Return the amount of tokens for a given Estate * @param estateId Estate id to search * @return Tokens length */ function getEstateSize(uint256 estateId) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /// @title ERC-721 Consumer Role extension /// Note: the ERC-165 identifier for this interface is 0x953c8dfa interface IERC721Consumable is IERC721 { /// @notice Emitted when `owner` changes the `consumer` of an NFT /// The zero address for consumer indicates that there is no consumer address /// When a Transfer event emits, this also indicates that the consumer address /// for that NFT (if any) is set to none event ConsumerChanged(address indexed owner, address indexed consumer, uint256 indexed tokenId); /// @notice Get the consumer address of an NFT /// @dev The zero address indicates that there is no consumer /// Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to get the consumer address for /// @return The consumer address for this NFT, or the zero address if there is none function consumerOf(uint256 _tokenId) view external returns (address); /// @notice Change or reaffirm the consumer address for an NFT /// @dev The zero address indicates there is no consumer address /// Throws unless `msg.sender` is the current NFT owner, an authorised /// operator of the current owner or approved address /// Throws if `_tokenId` is not valid NFT /// @param _consumer The new consumer of the NFT function changeConsumer(address _consumer, uint256 _tokenId) external; }
Stakes user's LandWorks NFTs tokenIds The tokenIds of the LandWorks NFTs which will be staked Transfer user's LandWorks NFTs to the staking contract Change the consumer of the LandWorks NFT to be the person who staked it Compute the amount/weight of the tokenId Increment the amount which will be staked Save the size, to be used on withdraw Save who is the staker/depositor of the token
function stake(uint256[] memory tokenIds) external nonReentrant whenNotPaused updateReward(msg.sender) { require(tokenIds.length != 0, "Staking: No tokenIds provided"); uint256 amount; for (uint256 i = 0; i < tokenIds.length; i += 1) { stakingToken.safeTransferFrom(msg.sender, address(this), tokenIds[i]); stakingToken.changeConsumer(msg.sender, tokenIds[i]); uint256 computedAmount = computeAmount(tokenIds[i]); amount += computedAmount; stakedAssetSizes[tokenIds[i]] = computedAmount; stakedAssets[tokenIds[i]] = msg.sender; } _stake(amount); emit Staked(msg.sender, amount, tokenIds); }
952,515
./full_match/1/0xB0A1Cd3b31A8e3bbBaba15fEDdB88ABD932a677d/sources/contracts/mixins/nftMarket/NFTMarketOffer.sol
@inheritdoc NFTMarketCore/
function _cancelSendersOffer(address nftContract, uint256 tokenId) internal override { Offer storage offer = nftContractToIdToOffer[nftContract][tokenId]; if (offer.buyer == _msgSender()) { _invalidateOffer(nftContract, tokenId); } }
8,357,024
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "./LotteryToken.sol"; import "./PriceConsumers.sol"; struct LotteryEvent { uint timestamp; string description; } struct Participant { //address participant; uint tokenId; } struct Range { uint min; uint max; } struct ChainlinkVRFData { address coordinator; address link; bytes32 keyHash; uint fee; } contract Lottery is VRFConsumerBase { enum State { WaitingForLINK, WaitingForParticipationPeriod, OngoingParticipationPeriod, OngoingPreparationPeriod, WaitingForNextEvent, WaitingForFundsRelease, Complete } uint8 public constant totalWinners = 3; uint8 public immutable chainTokenDecimals; // Chain token decimals (ETH, MATIC, ...) uint public immutable entryPriceUsd; address payable public immutable fundsReleaseAddress; LotteryToken public immutable token; // Periods uint public immutable beginningOfParticipationPeriod; uint public immutable endOfParticipationPeriod; uint public immutable endOfPreparationPeriod; // Events LotteryEvent[] public events; uint private remainingEventsCount; // Participants Participant[] public participants; Participant[] public winners; mapping(uint => bool) public winnersTokenId; Range[] public remainingParticipantsRanges; uint private remainingParticipantsCount; // Chainlink Price Feed PriceConsumer public immutable priceConsumer; // Chainlink VRF bytes32 public immutable vrfKeyHash; uint public immutable vrfFee; bool private vrfRequestingRandomness; constructor(uint8 _chainTokenDecimals, uint _entryPriceUsd, string memory _tokenName, string memory _tokenSymbol, string memory _CID, address payable _fundsReleaseAddress, uint _beginningOfParticipationPeriod, uint _endOfParticipationPeriod, uint _endOfPreparationPeriod, PriceConsumer _priceConsumer, ChainlinkVRFData memory _vrfData/*, LotteryEvent[] memory _events*/) VRFConsumerBase(_vrfData.coordinator, _vrfData.link) { // ####### Testing: FOR TESTING PURPOSES ONLY //_beginningOfParticipationPeriod = block.timestamp; //_endOfParticipationPeriod = _beginningOfParticipationPeriod + 60; //_endOfPreparationPeriod = _endOfParticipationPeriod + 60; LotteryEvent[2] memory _events = [ LotteryEvent({ timestamp: _endOfPreparationPeriod + 60, description: "Event1" }), LotteryEvent({ timestamp: _endOfPreparationPeriod + 120, description: "Event2" })]; //####### Testing // Validate periods require(_beginningOfParticipationPeriod > block.timestamp, "Invalid timestamp: beginningOfParticipationPeriod"); require(_endOfParticipationPeriod > _beginningOfParticipationPeriod, "Invalid timestamp: endOfParticipationPeriod"); require(_endOfPreparationPeriod > _endOfParticipationPeriod, "Invalid timestamp: endOfPreparationPeriod"); // Validate events require(_events.length > 0, "No events specified"); require(_events[0].timestamp >= _endOfPreparationPeriod, "Invalid timestamp: First event"); for(uint i = 0; i < _events.length; i++) { require(bytes(_events[i].description).length > 0, "Event has no description"); if(i > 0) { require(_events[i].timestamp > _events[i-1].timestamp, "Events timestamps not in ascending order"); } } // Since the following feature is not yet supported, manually copy the array to storage. // UnimplementedFeatureError: Copying of type struct LotteryEvent memory[] memory to storage not yet supported. for(uint i = 0; i < _events.length; i++) { events.push(_events[i]); } // Create lottery token token = new LotteryToken(this, _tokenName, _tokenSymbol, _CID); chainTokenDecimals = _chainTokenDecimals; entryPriceUsd = _entryPriceUsd; fundsReleaseAddress = _fundsReleaseAddress; beginningOfParticipationPeriod = _beginningOfParticipationPeriod; endOfParticipationPeriod = _endOfParticipationPeriod; endOfPreparationPeriod = _endOfPreparationPeriod; priceConsumer = _priceConsumer; remainingEventsCount = _events.length; vrfKeyHash = _vrfData.keyHash; vrfFee = _vrfData.fee; } /* * Triggers the next lottery event */ function triggerNextEvent() external { require(getState() == State.WaitingForNextEvent, "Not currently waiting for the next event"); uint nextEventIndex = _getNextEventIndex(); LotteryEvent memory nextEvent = events[nextEventIndex]; require(block.timestamp >= nextEvent.timestamp, "Too early to trigger the next event"); // Chainlink VRF require(!vrfRequestingRandomness, "Already requesting randomness"); requestRandomness(vrfKeyHash, vrfFee); vrfRequestingRandomness = true; // Do this early here to lower the gas used in fulfillRandomness() if(nextEventIndex == 0) { // First event remainingParticipantsCount = participants.length; remainingParticipantsRanges.push(Range({ min: 0, max: participants.length - 1 })); } } /* * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { Range[] memory mRanges = remainingParticipantsRanges; Range[] storage sRanges = remainingParticipantsRanges; delete(remainingParticipantsRanges); remainingParticipantsCount /= 2; // 50% halving if(remainingParticipantsCount < totalWinners) { // Can not halve anymore. In this case, the ranges are only shuffled. // The result is that 1st, 2nd, 3rd place are shuffled. remainingParticipantsCount = totalWinners; } if(mRanges.length == 1) { uint nextIndex = randomness % (mRanges[0].max - mRanges[0].min + 1) + mRanges[0].min; if(nextIndex + remainingParticipantsCount - 1 <= mRanges[0].max) { sRanges.push(Range({ min: nextIndex, max: nextIndex + remainingParticipantsCount - 1 })); } else { sRanges.push(Range({ min: nextIndex, max: mRanges[0].max })); sRanges.push(Range({ min: mRanges[0].min, max: mRanges[0].min + (remainingParticipantsCount - 1) - (mRanges[0].max - nextIndex + 1) })); } } else { uint firstRangeIndex = randomness % 2; uint nextIndex = randomness % (mRanges[firstRangeIndex].max - mRanges[firstRangeIndex].min + 1) + mRanges[firstRangeIndex].min; if(nextIndex + remainingParticipantsCount - 1 <= mRanges[firstRangeIndex].max) { sRanges.push(Range({ min: nextIndex, max: nextIndex + remainingParticipantsCount - 1 })); } else { uint secondRangeIndex = (firstRangeIndex + 1) % 2; // If first is 0 will be 1 and vice-versa uint participantsInFirstRange = mRanges[firstRangeIndex].max - nextIndex + 1; uint participantsInSecondRange = remainingParticipantsCount - participantsInFirstRange; uint secondRangeMaxIndex = mRanges[secondRangeIndex].min + participantsInSecondRange - 1; if(secondRangeMaxIndex >= participants.length) { uint surplus = secondRangeMaxIndex + 1 - participants.length; nextIndex -= surplus; } sRanges.push(Range({ min: nextIndex, max: mRanges[firstRangeIndex].max })); sRanges.push(Range({ min: mRanges[secondRangeIndex].min, max: mRanges[secondRangeIndex].min + (remainingParticipantsCount - 1) - (mRanges[firstRangeIndex].max - nextIndex + 1) })); } } vrfRequestingRandomness = false; remainingEventsCount--; // TODO: Emit event // uint nextEventIndex = _getNextEventIndex(); // LotteryEvent memory nextEvent = events[nextEventIndex]; if(remainingEventsCount == 0) { triggerCompletion(); } } uint public valueTest; function testFunc(uint256 value) external { valueTest = value; } /* * Participate in the lottery * ####### Testing Args: [[0,0,0,0,0,0]] */ function participate(SpaceShips.Ship memory spaceShip) external payable { // ####### Testing: COMMENT the following line require(getState() == State.OngoingParticipationPeriod, "Not currently accepting participants"); // ####### Testing uint entryPrice = getPriceToParticipate(); require(msg.value >= entryPrice, "Not enough funds to participate. See getPriceToParticipate()"); // Mint lottery ticket as an NFT uint tokenId = token.mint(msg.sender, spaceShip); // Register participation participants.push(Participant({ //participant: msg.sender, tokenId: tokenId })); } /* * Releases the funds to the lottery wallet */ function triggerCompletion() public { require(getState() == State.WaitingForFundsRelease, "Not currently waiting for funds release"); // Release funds _releaseFunds(); // Fill winners for(uint i = 0; i < remainingParticipantsRanges.length && winners.length < totalWinners; i++) { Range memory range = remainingParticipantsRanges[i]; for(uint j = range.min; j <= range.max && winners.length < totalWinners ; j++) { Participant memory winner = participants[j]; winners.push(winner); winnersTokenId[winner.tokenId] = true; } } // TODO: Emit completion event } /* * Releases the funds to the lottery wallet */ function _releaseFunds() private { fundsReleaseAddress.transfer(address(this).balance); } /* * Allows the funds to get released 14 days after the last event * This is a last resort option in case something goes wrong */ function releaseFundsLastResort() private { require(block.timestamp >= events[events.length - 1].timestamp + 3600 * 24 * 14, "Too early to release the funds"); _releaseFunds(); } /* * Returns the current lottery state */ function getState() public view returns(State) { if(getLINKAmountRequired() > 0) { return State.WaitingForLINK; } if(block.timestamp < beginningOfParticipationPeriod) { return State.WaitingForParticipationPeriod; } if(block.timestamp < endOfParticipationPeriod) { return State.OngoingParticipationPeriod; } if(block.timestamp < endOfPreparationPeriod) { return State.OngoingPreparationPeriod; } if(participants.length > 0 && remainingEventsCount > 0) { return State.WaitingForNextEvent; } if(address(this).balance > 0) { return State.WaitingForFundsRelease; } return State.Complete; } /* * Returns the amount of LINK required to fund the contract * LINK is used for per-event VRF computation */ function getLINKAmountRequired() public view returns(uint) { uint amountRequired = vrfFee * remainingEventsCount; uint currentBalance = LINK.balanceOf(address(this)); if(currentBalance < amountRequired) { return amountRequired - currentBalance; } return 0; } /* * Returns the price required to participate to the lottery */ function getPriceToParticipate() public view returns(uint) { int latestPrice = priceConsumer.getLatestPrice(); if(latestPrice <= 0) { // In the exceptional case of a 0 or negative price returned // from the oracle, set the entry price to 0 return 0; } // Adjust the price returned from the oracle to the full token's precision uint latestPriceAdjusted = uint(latestPrice) * 10 ** (chainTokenDecimals - priceConsumer.decimals()); // Calculate the token price based on the priceConsumer's token (ETH, MATIC, ...) uint entryPrice = 10 ** (chainTokenDecimals * 2) * entryPriceUsd / latestPriceAdjusted; return entryPrice; } /* * Gets the index of the next event */ function _getNextEventIndex() private view returns(uint) { return events.length - remainingEventsCount; } /* * Returns whether or not the lottery is completed */ function isComplete() public view returns(bool) { return getState() == State.Complete; } /* * Returns whether or not the ticket is a winning ticket */ function isWinningTicket(uint tokenId) public view returns(bool) { return winnersTokenId[tokenId]; } } /** * Network: Polygon ----------------- * VRF Coordinator (mainnet): 0x3d2341ADb2D31f1c5530cDC622016af293177AE0 * LINK (mainnet): 0xb0897686c545045aFc77CF20eC7A532E3120E0F1 * Key Hash (mainnet): 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da * Fee: 0.0001 LINK ----------------- * VRF Coordinator (testnet): 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255 * LINK (testnet): 0x326C977E6efc84E512bB9C30f76E30c160eD06FB * Key Hash (mainnet): 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4 * Fee: 0.0001 LINK ----------------- * From: https://docs.chain.link/docs/vrf-contracts/ */ contract LotteryTest is Lottery { constructor() Lottery(18, // Current chain token decimals. MATIC/ETH = 18 19, // Entry price. TESTING. Should be 19 "Test5424243243", // Token name "SS1", // Token symbol "bafybeidinazu3rqvapnd2qy55kpa5kj2t32xb5dq3bysrb76ccczv7rdse", // CID payable(0xf585378ff2A1DeCb335b4899250b83F46DC5c019), // Charity address block.timestamp + 60 * 5, // Participation period starts 5 minutes later block.timestamp + 60 * 10, // Preparation period starts 10 minutes later block.timestamp + 60 * 15, // Preparation period ends 15 minutes later new PriceConsumerMaticUSD(), // Chainlink Price Feed ChainlinkVRFData({ // Chainlink VRF coordinator: 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, link: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB, keyHash: 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4, fee: 0.0001 * 10 ** 18 })) { } } contract LotteryParticipationInfinite is Lottery { constructor() Lottery(18, // Current chain token decimals. MATIC/ETH = 18 0, // Entry price. TESTING. Should be 19 "SpaceTokenName", // Token name "STN", // Token symbol "bafybeidinazu3rqvapnd2qy55kpa5kj2t32xb5dq3bysrb76ccczv7rdse", // CID payable(0xf585378ff2A1DeCb335b4899250b83F46DC5c019), // Charity address block.timestamp + 1, // Participation period starts immediatly block.timestamp + 3600 * 24 * 998, // Preparation period starts 998 days later block.timestamp + 3600 * 24 * 999, // Preparation period ends 999 days later new PriceConsumerMaticUSD(), // Chainlink Price Feed ChainlinkVRFData({ // Chainlink VRF coordinator: 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, link: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB, keyHash: 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4, fee: 0.0001 * 10 ** 18 })) { } }
Releases the funds to the lottery wallet/
function _releaseFunds() private { fundsReleaseAddress.transfer(address(this).balance); }
7,229,842
// File: contracts/interface/ICoFiXV2Factory.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface ICoFiXV2Factory { // All pairs: {ETH <-> ERC20 Token} event PairCreated(address indexed token, address pair, uint256); event NewGovernance(address _new); event NewController(address _new); event NewFeeReceiver(address _new); event NewFeeVaultForLP(address token, address feeVault); event NewVaultForLP(address _new); event NewVaultForTrader(address _new); event NewVaultForCNode(address _new); event NewDAO(address _new); /// @dev Create a new token pair for trading /// @param token the address of token to trade /// @param initToken0Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @param initToken1Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @return pair the address of new token pair function createPair( address token, uint256 initToken0Amount, uint256 initToken1Amount ) external returns (address pair); function getPair(address token) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function getTradeMiningStatus(address token) external view returns (bool status); function setTradeMiningStatus(address token, bool status) external; function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs function setFeeVaultForLP(address token, address feeVault) external; function setGovernance(address _new) external; function setController(address _new) external; function setFeeReceiver(address _new) external; function setVaultForLP(address _new) external; function setVaultForTrader(address _new) external; function setVaultForCNode(address _new) external; function setDAO(address _new) external; function getController() external view returns (address controller); function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders function getVaultForLP() external view returns (address vaultForLP); function getVaultForTrader() external view returns (address vaultForTrader); function getVaultForCNode() external view returns (address vaultForCNode); function getDAO() external view returns (address dao); } // File: contracts/interface/ICoFiXERC20.sol pragma solidity 0.6.12; interface ICoFiXERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/interface/ICoFiXV2Pair.sol pragma solidity 0.6.12; interface ICoFiXV2Pair is ICoFiXERC20 { struct OraclePrice { uint256 ethAmount; uint256 erc20Amount; uint256 blockNum; uint256 K; uint256 theta; } // All pairs: {ETH <-> ERC20 Token} event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, address outToken, uint outAmount, address indexed to); event Swap( address indexed sender, uint amountIn, uint amountOut, address outToken, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1); function mint(address to, uint amountETH, uint amountToken) external payable returns (uint liquidity, uint oracleFeeChange); function burn(address tokenTo, address ethTo) external payable returns (uint amountTokenOut, uint amountETHOut, uint oracleFeeChange); function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[5] memory tradeInfo); // function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo); function skim(address to) external; function sync() external; function initialize(address, address, string memory, string memory, uint256, uint256) external; /// @dev get Net Asset Value Per Share /// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token} /// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token} /// @return navps The Net Asset Value Per Share (liquidity) represents function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps); /// @dev get initial asset ratio /// @return _initToken0Amount Token0(ETH) side of initial asset ratio {ETH <-> ERC20 Token} /// @return _initToken1Amount Token1(ERC20) side of initial asset ratio {ETH <-> ERC20 Token} function getInitialAssetRatio() external view returns (uint256 _initToken0Amount, uint256 _initToken1Amount); } // File: contracts/interface/INestPriceFacade.sol pragma solidity ^0.6.12; /// @dev This interface defines the methods for price call entry interface INestPriceFacade { // /// @dev Price call entry configuration structure // struct Config { // // Single query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 singleFee; // // Double query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 doubleFee; // // The normal state flag of the call address. 0 // uint8 normalFlag; // } // /// @dev Modify configuration // /// @param config Configuration object // function setConfig(Config memory config) external; // /// @dev Get configuration // /// @return Configuration object // function getConfig() external view returns (Config memory); /// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called /// @param addr Destination address /// @param flag Address flag function setAddressFlag(address addr, uint flag) external; /// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called /// @param addr Destination address /// @return Address flag function getAddressFlag(address addr) external view returns(uint); /// @dev Set INestQuery implemention contract address for token /// @param tokenAddress Destination token address /// @param nestQueryAddress INestQuery implemention contract address, 0 means delete function setNestQuery(address tokenAddress, address nestQueryAddress) external; /// @dev Get INestQuery implemention contract address for token /// @param tokenAddress Destination token address /// @return INestQuery implemention contract address, 0 means use default function getNestQuery(address tokenAddress) external view returns (address); /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ); /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice(address tokenAddress, uint height, address paybackAddress) external payable returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count, address paybackAddress) external payable returns (uint[] memory); /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress, address paybackAddress) external payable returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice); /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ); /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice); } // File: contracts/interface/ICoFiXV2Controller.sol pragma solidity 0.6.12; interface ICoFiXV2Controller { event NewK(address token, uint256 K, uint256 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum); event NewGovernance(address _new); event NewOracle(address _priceOracle); event NewKTable(address _kTable); event NewTimespan(uint256 _timeSpan); event NewKRefreshInterval(uint256 _interval); event NewKLimit(int128 maxK0); event NewGamma(int128 _gamma); event NewTheta(address token, uint32 theta); event NewK(address token, uint32 k); event NewCGamma(address token, uint32 gamma); function addCaller(address caller) external; function setCGamma(address token, uint32 gamma) external; function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta); function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta); function getLatestPriceAndAvgVola(address token) external payable returns (uint256, uint256, uint256, uint256); } // File: contracts/lib/TransferHelper.sol pragma solidity 0.6.12; // 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'); } } // File: contracts/lib/ABDKMath64x64.sol /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com> */ pragma solidity 0.6.12; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * @dev Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** * @dev Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1)); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << 127 - msb; for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= 63 - (x >> 64); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } // 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: contracts/CoFiXV2Controller.sol pragma solidity 0.6.12; // Controller contract to call NEST Oracle for prices, managed by governance // Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract contract CoFiXV2Controller is ICoFiXV2Controller { // ctrl-03: change contract name to avoid truffle complaint using SafeMath for uint256; enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX // uint256 constant public AONE = 1 ether; // uint256 constant public K_BASE = 1E8; uint256 constant public K_GAMMA_BASE = 10; uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy uint256 constant internal K_ALPHA = 2000; // α=2e-05*1e8 uint256 constant internal K_BETA = 4000000000; // β=40*1e8 uint256 internal T = 3600; // ctrl-v2: V1 (900) -> V2 (3600) uint256 internal K_EXPECTED_VALUE = 0.005*1E8; // ctrl-v2: V1 (0.0025) -> V2 (0.005) // impact cost params uint256 constant internal C_BUYIN_ALPHA = 0; // α=0 uint256 constant internal C_BUYIN_BETA = 20000000000000; // β=2e-05*1e18 uint256 constant internal C_SELLOUT_ALPHA = 0; // α=0 uint256 constant internal C_SELLOUT_BETA = 20000000000000; // β=2e-05*1e18 mapping(address => uint32) public CGammaMap; // int128 constant internal SIGMA_STEP = 0x346DC5D638865; // (0.00005*2**64).toString(16), 0.00005 as 64.64-bit fixed point // int128 constant internal ZERO_POINT_FIVE = 0x8000000000000000; // (0.5*2**64).toString(16) uint256 constant PRICE_DEVIATION = 10; // price deviation < 10% mapping(address => uint32[3]) internal KInfoMap; // gas saving, index [0] is k vlaue, index [1] is updatedAt, index [2] is theta mapping(address => bool) public callerAllowed; // managed by governance address public governance; address public immutable oracle; address public immutable nestToken; address public immutable factory; uint256 public timespan = 14; // uint256 public kRefreshInterval = 5 minutes; // uint256 public DESTRUCTION_AMOUNT = 0 ether; // from nest oracle // int128 public MAX_K0 = 0xCCCCCCCCCCCCD00; // (0.05*2**64).toString(16) // int128 public GAMMA = 0x8000000000000000; // (0.5*2**64).toString(16) struct OracleParams { uint256 ethAmount; uint256 erc20Amount; uint256 blockNum; uint256 K; uint256 T; // time offset uint256 avgPrice; // average price uint256 theta; uint256 sigma; uint256 tIdx; uint256 sigmaIdx; } modifier onlyGovernance() { require(msg.sender == governance, "CoFiXCtrl: !governance"); _; } constructor(address _oracle, address _nest, address _factory) public { governance = msg.sender; oracle = _oracle; nestToken = _nest; factory = _factory; // add previous pair as caller ICoFiXV2Factory cFactory = ICoFiXV2Factory(_factory); uint256 pairCnt = cFactory.allPairsLength(); for (uint256 i = 0; i < pairCnt; i++) { address pair = cFactory.allPairs(i); callerAllowed[pair] = true; } } receive() external payable {} /* setters for protocol governance */ function setGovernance(address _new) external onlyGovernance { governance = _new; emit NewGovernance(_new); } function setTimespan(uint256 _timeSpan) external onlyGovernance { timespan = _timeSpan; emit NewTimespan(_timeSpan); } // function setKRefreshInterval(uint256 _interval) external onlyGovernance { // kRefreshInterval = _interval; // emit NewKRefreshInterval(_interval); // } // function setOracleDestructionAmount(uint256 _amount) external onlyGovernance { // DESTRUCTION_AMOUNT = _amount; // } function setTLimit(uint256 _T) external onlyGovernance { // ctrl-v2: new setter for T T = _T; } function setK(address token, uint32 k) external onlyGovernance { // ctrl-v2: new setter for K, adjustable by governance K_EXPECTED_VALUE = uint256(k); emit NewK(token, k); // new event for setting K } function setTheta(address token, uint32 theta) external onlyGovernance { KInfoMap[token][2] = theta; emit NewTheta(token, theta); } function addCaller(address caller) external override { require(msg.sender == factory || msg.sender == governance, "CoFiXCtrl: only factory or gov"); callerAllowed[caller] = true; } function setCGamma(address token, uint32 gamma) external override onlyGovernance { CGammaMap[token] = gamma; emit NewCGamma(token, gamma); } // Calc variance of price and K in CoFiX is very expensive // We use expected value of K based on statistical calculations here to save gas // In the near future, NEST could provide the variance of price directly. We will adopt it then. // We can make use of `data` bytes in the future function queryOracle(address token, uint8 op, bytes memory data) external override payable returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum, uint256 _theta) { require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed"); (_k, _ethAmount, _erc20Amount, _blockNum) = getLatestPrice(token); CoFiX_OP cop = CoFiX_OP(op); uint256 impactCost; if (cop == CoFiX_OP.SWAP_WITH_EXACT) { impactCost = calcImpactCostFor_SWAP_WITH_EXACT(token, data, _ethAmount, _erc20Amount); } else if (cop == CoFiX_OP.SWAP_FOR_EXACT) { revert("disabled experimental feature!"); // ctrl-v2: disable swapForExact function } else if (cop == CoFiX_OP.BURN) { impactCost = calcImpactCostFor_BURN(token, data, _ethAmount, _erc20Amount); } _k = _k.add(impactCost); // ctrl-v2: adjustable K + impactCost is the final K _theta = KInfoMap[token][2]; return (_k, _ethAmount, _erc20Amount, _blockNum, _theta); } function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) { // bytes memory data = abi.encode(msg.sender, liquidity, initToken1Amount); (, uint256 liquidity) = abi.decode(data, (address, uint256)); (uint256 initToken0Amount, uint256 initToken1Amount) = ICoFiXV2Pair(msg.sender).getInitialAssetRatio(); // pair call controller, msg.sender is pair // calc real vol by liquidity * np uint256 navps = ICoFiXV2Pair(msg.sender).getNAVPerShare(ethAmount, erc20Amount); // pair call controller, msg.sender is pair // ethOut uint256 buyVol = liquidity.mul(navps).div(NAVPS_BASE); /* tokenOut = liquidity * navps * \frac{k_0}{P_t}\\\\ = liquidity * navps * \frac{initToken1Amount * ethAmount}{initToken0Amount * erc20Amount * NAVPS\_BASE} */ uint256 initToken1AmountMulEthAmount = initToken1Amount.mul(ethAmount); uint256 erc20AmountMulInitToken0Amount = erc20Amount.mul(initToken0Amount); uint256 sellOutVol = liquidity.mul(navps).mul(initToken1AmountMulEthAmount).div(erc20AmountMulInitToken0Amount).div(NAVPS_BASE); // buy in ETH, outToken is ETH uint256 impactCostForBuy = impactCostForBuyInETH(token, buyVol); // sell out liquidity, outToken is token, take this as sell out ETH and get token uint256 impactCostForSellOut = impactCostForSellOutETH(token, sellOutVol); return impactCostForBuy.add(impactCostForSellOut); } function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) { (, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256)); if (outToken != token) { // buy in ETH, outToken is ETH, amountIn is token // convert to amountIn in ETH uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount); return impactCostForBuyInETH(token, vol); } // sell out ETH, amountIn is ETH return impactCostForSellOutETH(token, amountIn); } function calcImpactCostFor_SWAP_FOR_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) { (, address outToken, uint256 amountOutExact,) = abi.decode(data, (address, address, uint256, address)); if (outToken != token) { // buy in ETH, outToken is ETH, amountOutExact is ETH return impactCostForBuyInETH(token, amountOutExact); } // sell out ETH, amountIn is ETH, amountOutExact is token // convert to amountOutExact in ETH uint256 vol = uint256(amountOutExact).mul(ethAmount).div(erc20Amount); return impactCostForSellOutETH(token, vol); } // impact cost // - C = 0, if VOL < 50 / γ // - C = (α + β * VOL) * γ, if VOL >= 50 / γ // α=0,β=2e-05 function impactCostForBuyInETH(address token, uint256 vol) public view returns (uint256 impactCost) { uint32 gamma = CGammaMap[token]; if (vol.mul(gamma) < 50 ether) { return 0; } // return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).mul(1e8).div(1e18); return (C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).div(1e10)).mul(gamma); // combine mul div } // α=0,β=2e-05 function impactCostForSellOutETH(address token, uint256 vol) public view returns (uint256 impactCost) { uint32 gamma = CGammaMap[token]; if (vol.mul(gamma) < 50 ether) { return 0; } // return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).mul(1e8).div(1e18); return ((C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).div(1e10)).mul(gamma); // combine mul div } function getKInfo(address token) external override view returns (uint32 k, uint32 updatedAt, uint32 theta) { // ctrl-v3: load from storage instead of constant value uint32 kStored = KInfoMap[token][0]; if (kStored != 0) { k = kStored; } else { k = uint32(K_EXPECTED_VALUE); } updatedAt = KInfoMap[token][1]; theta = KInfoMap[token][2]; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function getLatestPrice(address token) internal returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) { uint256 _balanceBefore = address(this).balance; OracleParams memory _op; // query oracle /// latestPriceBlockNumber The block number of latest price /// latestPriceValue The token latest price. (1eth equivalent to (price) token) /// triggeredPriceBlockNumber The block number of triggered price /// triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// triggeredAvgPrice Average price /// triggeredSigmaSQ The square of the volatility (18 decimal places). ( _op.blockNum, _op.erc20Amount, /* uint triggeredPriceBlockNumber */, /* uint triggeredPriceValue */, _op.avgPrice, _op.sigma ) = INestPriceFacade(oracle).latestPriceAndTriggeredPriceInfo{value: msg.value}(token, address(this)); _op.sigma = sqrt(_op.sigma.mul(1e18)); _op.ethAmount = 1 ether; // validate T _op.T = block.number.sub(_op.blockNum).mul(timespan); require(_op.T < T, "CoFiXCtrl: oralce price outdated"); // ctrl-v2: adjustable T { // check if the price is steady uint256 price; bool isDeviated; price = _op.erc20Amount.mul(1e18).div(_op.ethAmount); uint256 diff = price > _op.avgPrice? (price - _op.avgPrice) : (_op.avgPrice - price); isDeviated = (diff.mul(100) < _op.avgPrice.mul(PRICE_DEVIATION))? false : true; require(isDeviated == false, "CoFiXCtrl: price deviation"); // validate } // calc K // K=(0.00001*T+10*σ)*γ(σ) { uint256 gamma = calcGamma(_op.sigma); _k = K_ALPHA.mul(_op.T).mul(1e18).add(K_BETA.mul(_op.sigma)).mul(gamma).div(K_GAMMA_BASE).div(1e18); emit NewK(token, _k, _op.sigma, _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum); } { // return oracle fee change // we could decode data in the future to pay the fee change and mining award token directly to reduce call cost // TransferHelper.safeTransferETH(payback, msg.value.sub(_balanceBefore.sub(address(this).balance))); uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance)); if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); KInfoMap[token][0] = uint32(_k); KInfoMap[token][1] = uint32(block.timestamp); // 2106 return (_k, _op.ethAmount, _op.erc20Amount, _op.blockNum); } } /** * @notice Calc K value * @param vola The square of the volatility (18 decimal places). * @param bn The block number when (ETH, TOKEN) price takes into effective * @return k The K value */ function calcK(uint256 vola, uint256 bn) external view returns (uint32 k) { uint256 _T = block.number.sub(bn).mul(timespan); vola = sqrt(vola.mul(1e18)); uint256 gamma = calcGamma(vola); k = uint32(K_ALPHA.mul(_T).mul(1e18).add(K_BETA.mul(vola)).mul(gamma).div(K_GAMMA_BASE).div(1e18)); } function calcGamma(uint256 vola) public pure returns (uint256 gamma) { // (0.0003 0.0005) => (300000000000000 500000000000000) if (vola <= 300000000000000) { // 𝜎 ≤ 0.0003, gamma = 1 return 10; } else if (vola > 500000000000000) { // 𝜎 > 0.0005, gamma = 2 return 20; } else { // 0.0003 < 𝜎 ≤ 0.0005, gamma = 1.5 return 15; } } function getLatestPriceAndAvgVola(address token) public override payable returns (uint256, uint256, uint256, uint256) { require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed"); uint256 _balanceBefore = address(this).balance; ( uint256 bn, uint256 erc20Amount, /* uint triggeredPriceBlockNumber */, /* uint triggeredPriceValue */, uint256 avg, uint256 triggeredSigmaSQ ) = INestPriceFacade(oracle).latestPriceAndTriggeredPriceInfo{value: msg.value}(token, address(this)); uint256 vola = sqrt(triggeredSigmaSQ); // (uint256 ethAmount, uint256 erc20Amount, uint256 avg, int128 vola, uint256 bn) = // INestQuery(oracle).queryPriceAvgVola{value: msg.value}(token, address(this)); uint256 _T = block.number.sub(bn).mul(timespan); require(_T < T, "CoFiXCtrl: oralce price outdated"); // ctrl-v2: adjustable T uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance)); if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); return (1 ether, erc20Amount, avg, vola); } // ctrl-v2: remove unused code bellow according to PeckShield's advice }
query oracle validate T
function getLatestPrice(address token) internal returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) { uint256 _balanceBefore = address(this).balance; OracleParams memory _op; ( _op.blockNum, _op.erc20Amount, _op.avgPrice, _op.sigma _op.sigma = sqrt(_op.sigma.mul(1e18)); _op.ethAmount = 1 ether; _op.T = block.number.sub(_op.blockNum).mul(timespan); ) = INestPriceFacade(oracle).latestPriceAndTriggeredPriceInfo{value: msg.value}(token, address(this)); { uint256 price; bool isDeviated; price = _op.erc20Amount.mul(1e18).div(_op.ethAmount); uint256 diff = price > _op.avgPrice? (price - _op.avgPrice) : (_op.avgPrice - price); isDeviated = (diff.mul(100) < _op.avgPrice.mul(PRICE_DEVIATION))? false : true; } { uint256 gamma = calcGamma(_op.sigma); _k = K_ALPHA.mul(_op.T).mul(1e18).add(K_BETA.mul(_op.sigma)).mul(gamma).div(K_GAMMA_BASE).div(1e18); emit NewK(token, _k, _op.sigma, _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum); } { uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance)); if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); KInfoMap[token][0] = uint32(_k); return (_k, _op.ethAmount, _op.erc20Amount, _op.blockNum); } }
1,314,588
./partial_match/1/0x81e394999f2A7EcA904BB8b357d0aE7f22C02afa/sources/contracts/WomStakingProxy.sol
Collects wmxWom rewards from wmxRewardPool, converts any WOM deposited directly from the booster, and then applies the rewards to the wmxLocker, rewarding the caller in the process./update rewards
function queueNewRewards(address, uint256 _amount) external { if (_amount > 0) { IERC20(wom).safeTransferFrom(msg.sender, address(this), _amount); } if (womBal > 0) { uint256 womBalToSwap = womBal * swapShare / DENOMINATOR; uint256 amountOut; if (womSwapDepositorPool != address(0)) { (amountOut, ) = IPool(womSwapDepositorPool).quotePotentialSwap(wom, wmxWom, int256(womBalToSwap)); } if (amountOut > womBalToSwap) { IWomSwapDepositor(womSwapDepositor).deposit(womBalToSwap, address(0), amountOut, block.timestamp + 1); emit RewardsSwapped(womSwapDepositor, true, womBalToSwap, amountOut); womBalToSwap = 0; } uint256 womBalToDeposit = womBal - womBalToSwap; IWomDepositor(womDepositor).deposit(womBalToDeposit, address(0)); emit RewardsSwapped(womDepositor, false, womBalToDeposit, womBalToDeposit); } if (wmxWomBal > 0) { IWmxLocker(rewards).queueNewRewards(wmxWom, wmxWomBal); emit RewardsDistributed(wmxWom, wmxWomBal); } }
3,624,492
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "./Lib.sol"; /** * Actor use some data of a User Subject, generate the smart contract */ contract DataUsageContract { address private creator; uint private usageID = 0; mapping(uint => DataUsage) private dataUsages; // event for EVM logging event UseData(address indexed actorAddress, address indexed userAddress, uint indexed usageID, DataUsage dataUsage); /** * @dev generate a new contract */ constructor() { creator = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor } /** * Using this address, an actor can access the contract and execute function (Gα) based on its purpose of data processing. */ function useData(address userAddress, string memory serviceName, string memory servicePurpose, string memory operation, string[] memory personalData) public returns (uint) { address actorAddress = msg.sender; DataUsage memory dataUsage = DataUsage(actorAddress, userAddress, serviceName, servicePurpose, operation, personalData); usageID++; dataUsages[usageID] = dataUsage; // Log the deployment of DataUsage contract emit UseData(actorAddress, userAddress, usageID, dataUsage); return usageID; } /** * @dev get the data usage */ function retrieveDataUsage(uint _usageID) public view returns (DataUsage memory){ return dataUsages[_usageID]; } /** * @dev get the current contract address */ function getContractAddress() public view returns (address) { return address(this); } }
get the current contract address/
function getContractAddress() public view returns (address) { return address(this); }
12,977,828
pragma solidity ^0.4.25; /** * * ETH CRYPTOCURRENCY DISTRIBUTION PROJECT * Web site - https://two4ever.club * Telegram_chat - https://t.me/two4everClub * Twitter - https://twitter.com/ClubTwo4ever * Youtube - https://www.youtube.com/channel/UCl4-t8RS3-kEJIGQN6Xbtng * Email: - mailto:admin(at sign)two4ever.club * * --- Contract configuration: * - Daily payment of a deposit of 2% * - Minimal contribution 0.01 eth * - Currency and payment - ETH * - Contribution allocation schemes: * -- 5% Referral program (3% first level, 2% second level) * -- 7% Advertising * -- 5% Operating Expenses -- 83% dividend payments * * --- Referral Program: * - We have 2 level referral program. * - After your referral investment you will receive 3% of his investment * as one time bonus from 1 level and 2% form his referrals. * - To become your referral, you future referral should specify your address * in field DATA, while transferring ETH. * - When making the every deposit, the referral must indicate your wallet in the data field! * - You must have a deposit in the contract, otherwise the person invited by you will not be assigned to you * * --- Awards: * - The Best Investor * Largest investor becomes common referrer for investors without referrer * and get a lump sum of 3% of their deposits. To become winner you must invest * more than previous winner. * * - The Best Promoter * Investor with the most referrals becomes common referrer for investors without referrer * and get a lump sum of 2% of their deposits. To become winner you must invite more than * previous winner. * * --- About the Project: * ETH cryptocurrency distribution project * Blockchain-enabled smart contracts have opened a new era of trustless relationships without intermediaries. * This technology opens incredible financial possibilities. Our automated investment distribution model * is written into a smart contract, uploaded to the Ethereum blockchain and can be freely accessed online. * In order to insure our investors' complete secuirty, full control over the project has been transferred * from the organizers to the smart contract: nobody can influence the system's permanent autonomous functioning. * * --- How to invest: * 1. Send from ETH wallet to the smart contract address any amount from 0.01 ETH. * 2. Verify your transaction in the history of your application or etherscan.io, specifying the address * of your wallet. * --- How to get dividends: * Send 0 air to the address of the contract. Be careful. You can get your dividends only once every 24 hours. * * --- RECOMMENDED GAS PRICE: https://ethgasstation.info/ * You can check the payments on the etherscan.io site, in the "Internal Txns" tab of your wallet. * * ---It is not allowed to transfer from exchanges, only from your personal ETH wallet, for which you * have private keys. * * Contracts reviewed and approved by pros! * * Main contract - Two4ever. You can view the contract code by scrolling down. */ contract Storage { // define investor model struct investor { uint keyIndex; uint value; uint paymentTime; uint refs; uint refBonus; } // define bestAddress model for bestInvestor and bestPromoter struct bestAddress { uint value; address addr; } // statistic model struct recordStats { uint strg; uint invested; } struct Data { mapping(uint => recordStats) stats; mapping(address => investor) investors; address[] keys; bestAddress bestInvestor; bestAddress bestPromoter; } Data private d; // define log event when change value of "bestInvestor" or "bestPromoter" changed event LogBestInvestorChanged(address indexed addr, uint when, uint invested); event LogBestPromoterChanged(address indexed addr, uint when, uint refs); //creating contract constructor() public { d.keys.length++; } //insert new investor function insert(address addr, uint value) public returns (bool) { uint keyIndex = d.investors[addr].keyIndex; if (keyIndex != 0) return false; d.investors[addr].value = value; keyIndex = d.keys.length++; d.investors[addr].keyIndex = keyIndex; d.keys[keyIndex] = addr; updateBestInvestor(addr, d.investors[addr].value); return true; } // get full information about investor by "addr" function investorFullInfo(address addr) public view returns(uint, uint, uint, uint, uint) { return ( d.investors[addr].keyIndex, d.investors[addr].value, d.investors[addr].paymentTime, d.investors[addr].refs, d.investors[addr].refBonus ); } // get base information about investor by "addr" function investorBaseInfo(address addr) public view returns(uint, uint, uint, uint) { return ( d.investors[addr].value, d.investors[addr].paymentTime, d.investors[addr].refs, d.investors[addr].refBonus ); } // get short information about investor by "addr" function investorShortInfo(address addr) public view returns(uint, uint) { return ( d.investors[addr].value, d.investors[addr].refBonus ); } // get current Best Investor function getBestInvestor() public view returns(uint, address) { return ( d.bestInvestor.value, d.bestInvestor.addr ); } // get current Best Promoter function getBestPromoter() public view returns(uint, address) { return ( d.bestPromoter.value, d.bestPromoter.addr ); } // add referral bonus to address function addRefBonus(address addr, uint refBonus) public returns (bool) { if (d.investors[addr].keyIndex == 0) return false; d.investors[addr].refBonus += refBonus; return true; } // add referral bonus to address and update current Best Promoter value function addRefBonusWithRefs(address addr, uint refBonus) public returns (bool) { if (d.investors[addr].keyIndex == 0) return false; d.investors[addr].refBonus += refBonus; d.investors[addr].refs++; updateBestPromoter(addr, d.investors[addr].refs); return true; } //add amount of invest by the address of investor function addValue(address addr, uint value) public returns (bool) { if (d.investors[addr].keyIndex == 0) return false; d.investors[addr].value += value; updateBestInvestor(addr, d.investors[addr].value); return true; } // update statistics function updateStats(uint dt, uint invested, uint strg) public { d.stats[dt].invested += invested; d.stats[dt].strg += strg; } // get current statistics function stats(uint dt) public view returns (uint invested, uint strg) { return ( d.stats[dt].invested, d.stats[dt].strg ); } // update current "Best Investor" function updateBestInvestor(address addr, uint investorValue) internal { if(investorValue > d.bestInvestor.value){ d.bestInvestor.value = investorValue; d.bestInvestor.addr = addr; emit LogBestInvestorChanged(addr, now, d.bestInvestor.value); } } // update value of current "Best Promoter" function updateBestPromoter(address addr, uint investorRefs) internal { if(investorRefs > d.bestPromoter.value){ d.bestPromoter.value = investorRefs; d.bestPromoter.addr = addr; emit LogBestPromoterChanged(addr, now, d.bestPromoter.value); } } // set time of payment function setPaymentTime(address addr, uint paymentTime) public returns (bool) { if (d.investors[addr].keyIndex == 0) return false; d.investors[addr].paymentTime = paymentTime; return true; } // set referral bonus function setRefBonus(address addr, uint refBonus) public returns (bool) { if (d.investors[addr].keyIndex == 0) return false; d.investors[addr].refBonus = refBonus; return true; } // check if contains such address in storage function contains(address addr) public view returns (bool) { return d.investors[addr].keyIndex > 0; } // return current number of investors function size() public view returns (uint) { return d.keys.length; } } //contract for restricting access to special functionality contract Accessibility { address public owner; //access modifier modifier onlyOwner() { require(msg.sender == owner, "access denied"); _; } //constructor with assignment of contract holder value constructor() public { owner = msg.sender; } // deletion of contract holder function waiver() internal { delete owner; } } //main contract contract Two4ever is Accessibility { //connecting needed libraries using Helper for *; using Math for *; // define internal model of percents struct percent { uint val; uint den; } // contract name string public name; // define storage Storage private strg; // collection of key value pairs ffor referrals mapping(address => address) private referrals; //variable for admin address address public adminAddr; //variable for advertise address address public advertiseAddr; // time when start current wave uint public waveStartup; uint public totalInvestors; uint public totalInvested; // define constants //size of minimal investing uint public constant minInvesment = 10 finney; // 0.01 eth //max size of balance uint public constant maxBalance = 100000 ether; // time period when dividends can be accrued uint public constant dividendsPeriod = 24 hours; //24 hours // define contracts percents // percent of main dividends percent private dividends; // percent of admin interest percent private adminInterest ; // percent of 1-st level referral percent private ref1Bonus ; // percent of 2-nd level referral percent private ref2Bonus ; // percent of advertising interest percent private advertisePersent ; // event call when Balance has Changed event LogBalanceChanged(uint when, uint balance); // custom modifier for event broadcasting modifier balanceChanged { _; emit LogBalanceChanged(now, address(this).balance); } // constructor // creating contract. This function call once when contract is publishing. constructor() public { name = "two4ever.club"; // set admin address by account address who has published adminAddr = msg.sender; advertiseAddr = msg.sender; //define value of main percents dividends = percent(2, 100); // 2% adminInterest = percent(5, 100); // 5% ref1Bonus = percent(3, 100); // 3% ref2Bonus = percent(2, 100); // 2% advertisePersent = percent(7, 100); // 7% // start new wave startNewWave(); } // set the value of the wallet address for advertising expenses function setAdvertisingAddress(address addr) public onlyOwner { if(addr.notEmptyAddr()) { advertiseAddr = addr; } } //set the value of the wallet address for operating expenses function setAdminsAddress(address addr) public onlyOwner { if(addr.notEmptyAddr()) { adminAddr = addr; } } // deletion of contract holder function doWaiver() public onlyOwner { waiver(); } //functions is calling when transfer money to address of this contract function() public payable { // investor get him dividends when send value = 0 to address of this contract if (msg.value == 0) { getDividends(); return; } // getting referral address from data of request address a = msg.data.toAddr(); //call invest function invest(a); } // private function for get dividends function _getMydividends(bool withoutThrow) private { // get investor info Storage.investor memory investor = getMemInvestor(msg.sender); //check if investor exists if(investor.keyIndex <= 0){ if(withoutThrow){ return; } revert("sender is not investor"); } // calculate how many days have passed after last payment uint256 daysAfter = now.sub(investor.paymentTime).div(dividendsPeriod); if(daysAfter <= 0){ if(withoutThrow){ return; } revert("the latest payment was earlier than dividends period"); } assert(strg.setPaymentTime(msg.sender, now)); // calc valaue of dividends uint value = Math.div(Math.mul(dividends.val,investor.value),dividends.den) * daysAfter; // add referral bonus to dividends uint divid = value+ investor.refBonus; // check if enough money on balance of contract for payment if (address(this).balance < divid) { startNewWave(); return; } // send dividends and ref bonus if (investor.refBonus > 0) { assert(strg.setRefBonus(msg.sender, 0)); //send dividends and referral bonus to investor msg.sender.transfer(value+investor.refBonus); } else { //send dividends to investor msg.sender.transfer(value); } } // public function for calling get dividends function getDividends() public balanceChanged { _getMydividends(false); } // function for investing money from investor function invest(address ref) public payable balanceChanged { //check minimum requirements require(msg.value >= minInvesment, "msg.value must be >= minInvesment"); require(address(this).balance <= maxBalance, "the contract eth balance limit"); //save current money value uint value = msg.value; // ref system works only once for sender-referral if (!referrals[msg.sender].notEmptyAddr()) { //process first level of referrals if (notZeroNotSender(ref) && strg.contains(ref)) { //calc the reward uint reward = Math.div(Math.mul(ref1Bonus.val,value),ref1Bonus.den); assert(strg.addRefBonusWithRefs(ref, reward)); // referrer 1 bonus referrals[msg.sender] = ref; //process second level of referrals if (notZeroNotSender(referrals[ref]) && strg.contains(referrals[ref]) && ref != referrals[ref]) { //calc the reward reward = Math.div(Math.mul(ref2Bonus.val, value),ref2Bonus.den); assert(strg.addRefBonus(referrals[ref], reward)); // referrer 2 bonus } }else{ // get current Best Investor Storage.bestAddress memory bestInvestor = getMemBestInvestor(); // get current Best Promoter Storage.bestAddress memory bestPromoter = getMemBestPromoter(); if(notZeroNotSender(bestInvestor.addr)){ assert(strg.addRefBonus(bestInvestor.addr, Math.div(Math.mul(ref1Bonus.val, value),ref1Bonus.den))); // referrer 1 bonus referrals[msg.sender] = bestInvestor.addr; } if(notZeroNotSender(bestPromoter.addr)){ assert(strg.addRefBonus(bestPromoter.addr, Math.div(Math.mul(ref2Bonus.val, value),ref2Bonus.den))); // referrer 2 bonus referrals[msg.sender] = bestPromoter.addr; } } } _getMydividends(true); // send admins share adminAddr.transfer(Math.div(Math.mul(adminInterest.val, msg.value),adminInterest.den)); // send advertise share advertiseAddr.transfer(Math.div(Math.mul(advertisePersent.val, msg.value),advertisePersent.den)); // update statistics if (strg.contains(msg.sender)) { assert(strg.addValue(msg.sender, value)); strg.updateStats(now, value, 0); } else { assert(strg.insert(msg.sender, value)); strg.updateStats(now, value, 1); } assert(strg.setPaymentTime(msg.sender, now)); //increase count of investments totalInvestors++; //increase amount of investments totalInvested += msg.value; } /*views */ // show number of investors function investorsNumber() public view returns(uint) { return strg.size()-1; // -1 because see Storage constructor where keys.length++ } //show current contract balance function balanceETH() public view returns(uint) { return address(this).balance; } // show value of dividend percent function DividendsPercent() public view returns(uint) { return dividends.val; } // show value of admin percent function AdminPercent() public view returns(uint) { return adminInterest.val; } // show value of advertise persent function AdvertisePersent() public view returns(uint) { return advertisePersent.val; } // show value of referral of 1-st level percent function FirstLevelReferrerPercent() public view returns(uint) { return ref1Bonus.val; } // show value of referral of 2-nd level percent function SecondLevelReferrerPercent() public view returns(uint) { return ref2Bonus.val; } // show value of statisctics by date function statistic(uint date) public view returns(uint amount, uint user) { (amount, user) = strg.stats(date); } // show investor info by address function investorInfo(address addr) public view returns(uint value, uint paymentTime, uint refsCount, uint refBonus, bool isReferral) { (value, paymentTime, refsCount, refBonus) = strg.investorBaseInfo(addr); isReferral = referrals[addr].notEmptyAddr(); } // show best investor info function bestInvestor() public view returns(uint invested, address addr) { (invested, addr) = strg.getBestInvestor(); } // show best promoter info function bestPromoter() public view returns(uint refs, address addr) { (refs, addr) = strg.getBestPromoter(); } // return full investor info by address function getMemInvestor(address addr) internal view returns(Storage.investor) { (uint a, uint b, uint c, uint d, uint e) = strg.investorFullInfo(addr); return Storage.investor(a, b, c, d, e); } //return best investor info function getMemBestInvestor() internal view returns(Storage.bestAddress) { (uint value, address addr) = strg.getBestInvestor(); return Storage.bestAddress(value, addr); } //return best investor promoter function getMemBestPromoter() internal view returns(Storage.bestAddress) { (uint value, address addr) = strg.getBestPromoter(); return Storage.bestAddress(value, addr); } // check if address is not empty and not equal sender address function notZeroNotSender(address addr) internal view returns(bool) { return addr.notEmptyAddr() && addr != msg.sender; } /**end views */ // start wave function startNewWave() private { strg = new Storage(); totalInvestors = 0; waveStartup = now; } } // Math library with simple arithmetical functions library Math { //multiplying function mul(uint256 num1, uint256 num2) internal pure returns (uint256) { return num1 * num2; if (num1 == 0) { return 0; } return num1 * num2; } //divide function div(uint256 num1, uint256 num2) internal pure returns (uint256) { uint256 result = 0; require(num2 > 0); result = num1 / num2; return result; } //subtract function sub(uint256 num1, uint256 num2) internal pure returns (uint256) { require(num2 <= num1); uint256 result = 0; result = num1 - num2; return result; } //add function add(uint256 num1, uint256 num2) internal pure returns (uint256) { uint256 result = num1 + num2; require(result >= num1); return result; } //module function mod(uint256 num1, uint256 num2) internal pure returns (uint256) { require(num2 != 0); return num1 % num2; } } // Helper library with simple additional functions library Helper{ //check if the address is not empty function notEmptyAddr(address addr) internal pure returns(bool) { return !(addr == address(0)); } //check if the address is empty function isEmptyAddr(address addr) internal pure returns(bool) { return addr == address(0); } // convert to address function toAddr(uint source) internal pure returns(address) { return address(source); } //convert from bytes to address function toAddr(bytes source) internal pure returns(address addr) { assembly { addr := mload(add(source,0x14)) } return addr; } }
add amount of invest by the address of investor
function addValue(address addr, uint value) public returns (bool) { if (d.investors[addr].keyIndex == 0) return false; d.investors[addr].value += value; updateBestInvestor(addr, d.investors[addr].value); return true; }
6,410,439
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "./TokenVesting.sol"; contract FundsDistributor is TokenVesting { /// @notice identifier for the contract string public identifier; /** * @notice Construct a new Funds Distributor Contract * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not * @param _identifier unique identifier for the contract */ constructor(address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable, string memory _identifier) TokenVesting(beneficiary, start, cliffDuration, duration, revocable) public { identifier = _identifier; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); event TokensReleasedToAccount(address token, address receiver, uint256 amount); event VestingRevoked(address token); event BeneficiaryChanged(address newBeneficiary); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private immutable _cliff; uint256 private immutable _start; uint256 private immutable _duration; bool private immutable _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public { require(beneficiary != address(0), "TokenVesting::constructor: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(cliffDuration <= duration, "TokenVesting::constructor: cliff is longer than duration"); require(duration > 0, "TokenVesting::constructor: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(duration) > block.timestamp, "TokenVesting::constructor: final time is before current time"); _beneficiary = beneficiary; _revocable = revocable; _duration = duration; _cliff = start.add(cliffDuration); _start = start; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting::release: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Transfers vested tokens to given address. * @param token ERC20 token which is being vested * @param receiver Address receiving the token * @param amount Amount of tokens to be transferred */ function releaseToAddress(IERC20 token, address receiver, uint256 amount) public { require(_msgSender() == _beneficiary, "TokenVesting::setBeneficiary: Not contract beneficiary"); require(amount > 0, "TokenVesting::_releaseToAddress: amount should be greater than 0"); require(receiver != address(0), "TokenVesting::_releaseToAddress: receiver is the zero address"); uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting::_releaseToAddress: no tokens are due"); require(unreleased >= amount, "TokenVesting::_releaseToAddress: enough tokens not vested yet"); _released[address(token)] = _released[address(token)].add(amount); token.safeTransfer(receiver, amount); emit TokensReleasedToAccount(address(token), receiver, amount); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenVesting::revoke: cannot revoke"); require(!_revoked[address(token)], "TokenVesting::revoke: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit VestingRevoked(address(token)); } /** * @notice Change the beneficiary of the contract * @param newBeneficiary The new beneficiary address for the Contract */ function setBeneficiary(address newBeneficiary) public { require(_msgSender() == _beneficiary, "TokenVesting::setBeneficiary: Not contract beneficiary"); require(_beneficiary != newBeneficiary, "TokenVesting::setBeneficiary: Same beneficiary address as old"); _beneficiary = newBeneficiary; emit BeneficiaryChanged(newBeneficiary); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); } } /** * @dev Returns the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(IERC20 token) public view returns (uint256) { return _vestedAmount(token); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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; } }
return the amount of the token released./
function released(address token) public view returns (uint256) { return _released[token]; }
56,403
./full_match/97/0xe3FE30C8B0CA24418645Ce4F1d381F1d5C4c22E4/sources/contracts/Marketplace.sol
require(nft.isApprovedForAll(_msgSender(), address(this)), "item not approved"); _validPayToken(_payToken); _payToken = 0xe11A86849d99F524cAC3E7A0Ec1241828e332C62; TODO: Remove this- Static pay token address for now
function listItem( address _nftAddress, uint256 _tokenId, uint256 _quantity, address _payToken, uint256 _pricePerItem, uint256 _startingTime ) external notListed(_nftAddress, _tokenId, _msgSender()) { IERC721 nft = IERC721(_nftAddress); require(nft.ownerOf(_tokenId) == _msgSender(), "not owning item"); listings[_nftAddress][_tokenId][_msgSender()] = Listing(_quantity, _payToken, _pricePerItem, _startingTime); _nftCollectionAddress.add(_nftAddress); _nftCollectionTokenId.add(_tokenId); emit ItemListed(_msgSender(), _nftAddress, _tokenId, _quantity, _payToken, _pricePerItem, _startingTime); }
5,027,247
pragma solidity 0.6.12; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; /** ∩~~~~∩ ξ ・×・ ξ ξ ~ ξ ξ   ξ ξ   “~~~~〇 ξ       ξ ξ ξ ξ~~~ξ ξ ξ   ξ_ξξ_ξ ξ_ξξ_ξ */ // Grazing Range allows users to stake ibALPACA to receive various rewards contract GrazingRange is OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many Staking tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each reward distribution campaign. struct CampaignInfo { IERC20 stakingToken; // Address of Staking token contract. IERC20 rewardToken; // Address of Reward token contract uint256 startBlock; // start block of the campaign uint256 lastRewardBlock; // Last block number that Reward Token distribution occurs. uint256 accRewardPerShare; // Accumulated Reward Token per share, times 1e12. See below. uint256 totalStaked; // total staked amount each campaign's stake token, typically, each campaign has the same stake token, so need to track it separatedly uint256 totalRewards; } // Reward info struct RewardInfo { uint256 endBlock; uint256 rewardPerBlock; } // @dev this is mostly used for extending reward period // @notice Reward info is a set of {endBlock, rewardPerBlock} // indexed by campaigh ID mapping(uint256 => RewardInfo[]) public campaignRewardInfo; // @notice Info of each campaign. mapped from campaigh ID CampaignInfo[] public campaignInfo; // Info of each user that stakes Staking tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // @notice limit length of reward info // how many phases are allowed uint256 public rewardInfoLimit; // @dev reward holder account address public rewardHolder; event Deposit(address indexed user, uint256 amount, uint256 campaign); event Withdraw(address indexed user, uint256 amount, uint256 campaign); event EmergencyWithdraw(address indexed user, uint256 amount, uint256 campaign); event AddCampaignInfo(uint256 indexed campaignID, IERC20 stakingToken, IERC20 rewardToken, uint256 startBlock); event AddRewardInfo(uint256 indexed campaignID, uint256 indexed phase, uint256 endBlock, uint256 rewardPerBlock); event SetRewardInfoLimit(uint256 rewardInfoLimit); event SetRewardHolder(address rewardHolder); function initialize(address _rewardHolder) external initializer { OwnableUpgradeSafe.__Ownable_init(); ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init(); rewardInfoLimit = 52; // 52 weeks, 1 year rewardHolder = _rewardHolder; } // @notice function for setting a reward holder who is responsible for adding a reward info function setRewardHolder(address _rewardHolder) external onlyOwner { rewardHolder = _rewardHolder; emit SetRewardHolder(_rewardHolder); } // @notice set new reward info limit function setRewardInfoLimit(uint256 _updatedRewardInfoLimit) external onlyOwner { rewardInfoLimit = _updatedRewardInfoLimit; emit SetRewardInfoLimit(rewardInfoLimit); } // @notice reward campaign, one campaign represents a pair of staking and reward token, last reward Block and acc reward Per Share function addCampaignInfo(IERC20 _stakingToken, IERC20 _rewardToken, uint256 _startBlock) external onlyOwner { campaignInfo.push(CampaignInfo({ stakingToken: _stakingToken, rewardToken: _rewardToken, startBlock: _startBlock, lastRewardBlock: _startBlock, accRewardPerShare: 0, totalStaked: 0, totalRewards: 0 })); emit AddCampaignInfo(campaignInfo.length-1, _stakingToken, _rewardToken, _startBlock); } // @notice if the new reward info is added, the reward & its end block will be extended by the newly pushed reward info. function addRewardInfo(uint256 _campaignID, uint256 _endBlock, uint256 _rewardPerBlock) external onlyOwner { RewardInfo[] storage rewardInfo = campaignRewardInfo[_campaignID]; CampaignInfo storage campaign = campaignInfo[_campaignID]; require(rewardInfo.length < rewardInfoLimit, "GrazingRange::addRewardInfo::reward info length exceeds the limit"); require(rewardInfo.length == 0 || rewardInfo[rewardInfo.length - 1].endBlock >= block.number, "GrazingRange::addRewardInfo::reward period ended"); require(rewardInfo.length == 0 || rewardInfo[rewardInfo.length - 1].endBlock < _endBlock, "GrazingRange::addRewardInfo::bad new endblock"); uint256 startBlock = rewardInfo.length == 0 ? campaign.startBlock : rewardInfo[rewardInfo.length - 1].endBlock; uint256 blockRange = _endBlock.sub(startBlock); uint256 totalRewards = _rewardPerBlock.mul(blockRange); campaign.rewardToken.safeTransferFrom(rewardHolder, address(this), totalRewards); campaign.totalRewards = campaign.totalRewards.add(totalRewards); rewardInfo.push(RewardInfo({ endBlock: _endBlock, rewardPerBlock: _rewardPerBlock })); emit AddRewardInfo(_campaignID, rewardInfo.length-1, _endBlock, _rewardPerBlock); } function rewardInfoLen(uint256 _campaignID) external view returns (uint256) { return campaignRewardInfo[_campaignID].length; } function campaignInfoLen() external view returns (uint256) { return campaignInfo.length; } // @notice this will return end block based on the current block number. function currentEndBlock(uint256 _campaignID) external view returns (uint256) { return _endBlockOf(_campaignID, block.number); } function _endBlockOf(uint256 _campaignID, uint256 _blockNumber) internal view returns (uint256) { RewardInfo[] memory rewardInfo = campaignRewardInfo[_campaignID]; uint256 len = rewardInfo.length; if (len == 0) { return 0; } for (uint256 i = 0; i < len; ++i) { if (_blockNumber <= rewardInfo[i].endBlock) return rewardInfo[i].endBlock; } // @dev when couldn't find any reward info, it means that _blockNumber exceed endblock // so return the latest reward info. return rewardInfo[len-1].endBlock; } // @notice this will return reward per block based on the current block number. function currentRewardPerBlock(uint256 _campaignID) external view returns (uint256) { return _rewardPerBlockOf(_campaignID, block.number); } function _rewardPerBlockOf(uint256 _campaignID, uint256 _blockNumber) internal view returns (uint256) { RewardInfo[] memory rewardInfo = campaignRewardInfo[_campaignID]; uint256 len = rewardInfo.length; if (len == 0) { return 0; } for (uint256 i = 0; i < len; ++i) { if (_blockNumber <= rewardInfo[i].endBlock) return rewardInfo[i].rewardPerBlock; } // @dev when couldn't find any reward info, it means that timestamp exceed endblock // so return 0 return 0; } // @notice Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to, uint256 _endBlock) public pure returns (uint256) { if ((_from >= _endBlock) || (_from > _to)) { return 0; } if (_to <= _endBlock) { return _to.sub(_from); } return _endBlock.sub(_from); } // @notice View function to see pending Reward on frontend. function pendingReward(uint256 _campaignID, address _user) external view returns (uint256) { return _pendingReward(_campaignID, userInfo[_campaignID][_user].amount, userInfo[_campaignID][_user].rewardDebt); } function _pendingReward(uint256 _campaignID, uint256 _amount, uint256 _rewardDebt) internal view returns (uint256) { CampaignInfo memory campaign = campaignInfo[_campaignID]; RewardInfo[] memory rewardInfo = campaignRewardInfo[_campaignID]; uint256 accRewardPerShare = campaign.accRewardPerShare; if (block.number > campaign.lastRewardBlock && campaign.totalStaked != 0) { uint256 cursor = campaign.lastRewardBlock; for (uint256 i = 0; i < rewardInfo.length; ++i) { uint256 multiplier = getMultiplier(cursor, block.number, rewardInfo[i].endBlock); if (multiplier == 0) continue; cursor = rewardInfo[i].endBlock; accRewardPerShare = accRewardPerShare.add(multiplier.mul(rewardInfo[i].rewardPerBlock).mul(1e12).div(campaign.totalStaked)); } } return _amount.mul(accRewardPerShare).div(1e12).sub(_rewardDebt); } function updateCampaign(uint256 _campaignID) external nonReentrant { _updateCampaign(_campaignID); } // @notice Update reward variables of the given campaign to be up-to-date. function _updateCampaign(uint256 _campaignID) internal { CampaignInfo storage campaign = campaignInfo[_campaignID]; RewardInfo[] memory rewardInfo = campaignRewardInfo[_campaignID]; if (block.number <= campaign.lastRewardBlock) { return; } if (campaign.totalStaked == 0) { // if there is no total supply, return and use the campaign's start block as the last reward block // so that ALL reward will be distributed. // however, if the first deposit is out of reward period, last reward block will be its block number // in order to keep the multiplier = 0 if (block.number > _endBlockOf(_campaignID, block.number)) { campaign.lastRewardBlock = block.number; } return; } // @dev for each reward info for (uint256 i = 0; i < rewardInfo.length; ++i) { // @dev get multiplier based on current Block and rewardInfo's end block // multiplier will be a range of either (current block - campaign.lastRewardBlock) // or (reward info's endblock - campaign.lastRewardBlock) or 0 uint256 multiplier = getMultiplier(campaign.lastRewardBlock, block.number, rewardInfo[i].endBlock); if (multiplier == 0) continue; // @dev if currentBlock exceed end block, use end block as the last reward block // so that for the next iteration, previous endBlock will be used as the last reward block if (block.number > rewardInfo[i].endBlock) { campaign.lastRewardBlock = rewardInfo[i].endBlock; } else { campaign.lastRewardBlock = block.number; } campaign.accRewardPerShare = campaign.accRewardPerShare.add(multiplier.mul(rewardInfo[i].rewardPerBlock).mul(1e12).div(campaign.totalStaked)); } } // @notice Update reward variables for all campaigns. gas spending is HIGH in this method call, BE CAREFUL function massUpdateCampaigns() external nonReentrant { uint256 length = campaignInfo.length; for (uint256 pid = 0; pid < length; ++pid) { _updateCampaign(pid); } } // @notice Stake Staking tokens to GrazingRange function deposit(uint256 _campaignID, uint256 _amount) external nonReentrant { CampaignInfo storage campaign = campaignInfo[_campaignID]; UserInfo storage user = userInfo[_campaignID][msg.sender]; _updateCampaign(_campaignID); if (user.amount > 0) { uint256 pending = user.amount.mul(campaign.accRewardPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { campaign.rewardToken.safeTransfer(address(msg.sender), pending); } } if (_amount > 0) { campaign.stakingToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); campaign.totalStaked = campaign.totalStaked.add(_amount); } user.rewardDebt = user.amount.mul(campaign.accRewardPerShare).div(1e12); emit Deposit(msg.sender, _amount, _campaignID); } // @notice Withdraw Staking tokens from STAKING. function withdraw(uint256 _campaignID, uint256 _amount) external nonReentrant { _withdraw(_campaignID, _amount); } // @notice internal method for withdraw (withdraw and harvest method depend on this method) function _withdraw(uint256 _campaignID, uint256 _amount) internal { CampaignInfo storage campaign = campaignInfo[_campaignID]; UserInfo storage user = userInfo[_campaignID][msg.sender]; require(user.amount >= _amount, "GrazingRange::withdraw::bad withdraw amount"); _updateCampaign(_campaignID); uint256 pending = user.amount.mul(campaign.accRewardPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { campaign.rewardToken.safeTransfer(address(msg.sender), pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); campaign.stakingToken.safeTransfer(address(msg.sender), _amount); campaign.totalStaked = campaign.totalStaked.sub(_amount); } user.rewardDebt = user.amount.mul(campaign.accRewardPerShare).div(1e12); emit Withdraw(msg.sender, _amount, _campaignID); } // @notice method for harvest campaigns (used when the user want to claim their reward token based on specified campaigns) function harvest(uint256[] calldata _campaignIDs) external nonReentrant { for (uint256 i = 0; i < _campaignIDs.length; ++i) { _withdraw(_campaignIDs[i], 0); } } // @notice Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _campaignID) external nonReentrant { CampaignInfo storage campaign = campaignInfo[_campaignID]; UserInfo storage user = userInfo[_campaignID][msg.sender]; uint256 _amount = user.amount; campaign.totalStaked = campaign.totalStaked.sub(_amount); user.amount = 0; user.rewardDebt = 0; campaign.stakingToken.safeTransfer(address(msg.sender), _amount); emit EmergencyWithdraw(msg.sender, _amount, _campaignID); } // @notice Withdraw reward. EMERGENCY ONLY. function emergencyRewardWithdraw(uint256 _campaignID, uint256 _amount, address _beneficiary) external onlyOwner nonReentrant { CampaignInfo storage campaign = campaignInfo[_campaignID]; uint256 currentStakingPendingReward = _pendingReward(_campaignID, campaign.totalStaked, 0); require(currentStakingPendingReward.add(_amount) <= campaign.totalRewards, "GrazingRange::emergencyRewardWithdraw::not enough reward token"); campaign.totalRewards = campaign.totalRewards.sub(_amount); campaign.rewardToken.safeTransfer(_beneficiary, _amount); } }
if the new reward info is added, the reward & its end block will be extended by the newly pushed reward info.
function addRewardInfo(uint256 _campaignID, uint256 _endBlock, uint256 _rewardPerBlock) external onlyOwner { RewardInfo[] storage rewardInfo = campaignRewardInfo[_campaignID]; CampaignInfo storage campaign = campaignInfo[_campaignID]; require(rewardInfo.length < rewardInfoLimit, "GrazingRange::addRewardInfo::reward info length exceeds the limit"); require(rewardInfo.length == 0 || rewardInfo[rewardInfo.length - 1].endBlock >= block.number, "GrazingRange::addRewardInfo::reward period ended"); require(rewardInfo.length == 0 || rewardInfo[rewardInfo.length - 1].endBlock < _endBlock, "GrazingRange::addRewardInfo::bad new endblock"); uint256 startBlock = rewardInfo.length == 0 ? campaign.startBlock : rewardInfo[rewardInfo.length - 1].endBlock; uint256 blockRange = _endBlock.sub(startBlock); uint256 totalRewards = _rewardPerBlock.mul(blockRange); campaign.rewardToken.safeTransferFrom(rewardHolder, address(this), totalRewards); campaign.totalRewards = campaign.totalRewards.add(totalRewards); rewardInfo.push(RewardInfo({ endBlock: _endBlock, rewardPerBlock: _rewardPerBlock })); emit AddRewardInfo(_campaignID, rewardInfo.length-1, _endBlock, _rewardPerBlock); }
7,247,498
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "./interfaces/IDappState.sol"; import "./DappLib.sol"; import "./interfaces/IERC721.sol"; import "./interfaces/IERC721Receiver.sol"; import "./interfaces/IERC721Metadata.sol"; import "./imports/custom_nft/Address.sol"; import "./imports/custom_nft/Context.sol"; import "./imports/custom_nft/Strings.sol"; import "./imports/custom_nft/ERC165.sol"; /********************************************************************************************/ /* This contract is auto-generated based on your choices in DappStarter. You can make */ /* changes, but be aware that generating a new DappStarter project will require you to */ /* merge changes. One approach you can take is to make changes in Dapp.sol and have it */ /* call into this one. You can maintain all your data in this contract and your app logic */ /* in Dapp.sol. This lets you update and deploy Dapp.sol with revised code and still */ /* continue using this one. */ /********************************************************************************************/ contract DappState is IDappState, Context, ERC165, IERC721, IERC721Metadata { // Allow DappLib(SafeMath) functions to be called for all uint256 types // (similar to "prototype" in Javascript) using DappLib for uint256; using Address for address; using Strings for uint256; /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ S T A T E @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ // Account used to deploy contract address private contractOwner; // 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; /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Track authorized admins count to prevent lockout uint256 private authorizedAdminsCount = 1; // Admins authorized to manage contract mapping(address => uint256) private authorizedAdmins; /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ C O N S T R U C T O R @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ constructor() { contractOwner = msg.sender; /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Add account that deployed contract as an authorized admin authorizedAdmins[msg.sender] = 1; } /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ E V E N T S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ M O D I F I E R S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Modifier that requires the function caller to be a contract admin */ modifier requireContractAdmin() { require(isContractAdmin(msg.sender), "Caller is not a contract administrator"); // Modifiers require an "_" which indicates where the function body will be added _; } /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ F U N C T I O N S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /** * @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 setName(string memory name_) public virtual { _name = name_; } /** * @dev See {IERC721Metadata-symbol}. */ function setSymbol(string memory symbol_) public virtual { _symbol = symbol_; } /** * @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 = DappState.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 ) public 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 = DappState.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) external virtual requireContractAdmin { _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 ) public virtual requireContractAdmin { _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) public virtual requireContractAdmin { address owner = DappState.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(DappState.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) public virtual requireContractAdmin { _tokenApprovals[tokenId] = to; emit Approval(DappState.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 {} function asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Checks if an account is an admin * * @param account Address of the account to check */ function isContractAdmin ( address account ) public view returns(bool) { return authorizedAdmins[account] == 1; } /** * @dev Adds a contract admin * * @param account Address of the admin to add */ function addContractAdmin ( address account ) external requireContractAdmin { require(account != address(0), "Invalid address"); require(authorizedAdmins[account] < 1, "Account is already an administrator"); authorizedAdmins[account] = 1; authorizedAdminsCount++; } /** * @dev Removes a previously added admin * * @param account Address of the admin to remove */ function removeContractAdmin ( address account ) external requireContractAdmin { require(account != address(0), "Invalid address"); require(authorizedAdminsCount >= 2, "Cannot remove last admin"); delete authorizedAdmins[account]; authorizedAdminsCount--; } /** * @dev Removes the last admin fully decentralizing the contract * * @param account Address of the admin to remove */ function removeLastContractAdmin ( address account ) external requireContractAdmin { require(account != address(0), "Invalid address"); require(authorizedAdminsCount == 1, "Not the last admin"); delete authorizedAdmins[account]; authorizedAdminsCount--; } // Example functions that demonstrate how to call into this contract that holds state from // another contract. Look in ~/interfaces/IDappState.sol for the interface definitions and // in Dapp.sol for the actual calls into this contract. /** * @dev This is an EXAMPLE function that illustrates how functions in this contract can be * called securely from another contract to READ state data. Using the Contract Access * block will enable you to make your contract more secure by restricting which external * contracts can call functions in this contract. */ function getContractOwner() external view override returns(address) { return contractOwner; } uint256 counter; // This is an example variable used only to demonstrate calling // a function that writes state from an external contract. It and // "incrementCounter" and "getCounter" functions can (should?) be deleted. /** * @dev This is an EXAMPLE function that illustrates how functions in this contract can be * called securely from another contract to WRITE state data. Using the Contract Access * block will enable you to make your contract more secure by restricting which external * contracts can call functions in this contract. */ function incrementCounter ( uint256 increment ) external override // Enable the modifier below if using the Contract Access feature // requireContractAuthorized { // NOTE: If another contract is calling this function, then msg.sender will be the address // of the calling contract and NOT the address of the user who initiated the // transaction. It is possible to get the address of the user, but this is // spoofable and therefore not recommended. require(increment > 0 && increment < 10, "Invalid increment value"); counter = counter.add(increment); // Demonstration of using SafeMath to add to a number // While verbose, using SafeMath everywhere that you // add/sub/div/mul will ensure your contract does not // have weird overflow bugs. } /** * @dev This is an another EXAMPLE function that illustrates how functions in this contract can be * called securely from another contract to READ state data. Using the Contract Access * block will enable you to make your contract more secure by restricting which external * contracts can call functions in this contract. */ function getCounter() external view override returns(uint256) { return counter; } }
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); }
12,748,475
./partial_match/1/0x73CaEf5525CcED9d711d2b9AC932d023484aBb20/sources/MarioInu.sol
exclude from paying fees or having max transaction amount
constructor(Params memory params) { _name = "Mario Inu"; _symbol = "MARIO"; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); _totalSupply = 420_690_000_000_000 * 1e18; maxTransactionAmount = _totalSupply; maxWallet = _totalSupply; buyTreasuryFee = params.buyTreasuryFee; buyLiquidityFee = params.buyLiquidityFee; buyDevFee = params.buyDevFee; buyTotalFees = buyTreasuryFee + buyLiquidityFee + buyDevFee; sellTreasuryFee = params.sellTreasuryFee; sellLiquidityFee = params.sellLiquidityFee; sellDevFee = params.sellDevFee; sellTotalFees = sellTreasuryFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(treasury), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(treasury), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, _totalSupply);
15,549,074
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./interfaces/IERC2981.sol"; contract GachaAuction is Ownable, Pausable, ReentrancyGuard { using Counters for Counters.Counter; struct Drop { address tokenAddress; uint256 price; address paymentReceiver; uint64 notBefore; uint64 deadline; uint256[] tokenIds; } event DropCreated(address indexed seller, uint256 dropId); event DropUpdated(address indexed seller, uint256 dropId); event RoyaltyWithheld(address royaltyRecipient, uint256 royaltyAmount); event Sale(uint256 indexed dropId, uint256 tokenId, address buyer); Counters.Counter private _dropIdCounter; mapping(uint256 => Drop) private drops; mapping(uint256 => address) public dropSellers; address private _auctionFeeRecipient; uint256 private _auctionFeeBps; constructor(uint256 auctionFeeBps_, address auctionFeeRecipient_) Ownable() Pausable() ReentrancyGuard() { _auctionFeeBps = auctionFeeBps_; _auctionFeeRecipient = auctionFeeRecipient_; } /// @notice Given a drop struct, kicks off a new drop function setup(Drop calldata drop_) external whenNotPaused returns (uint256) { uint256 dropId = _dropIdCounter.current(); drops[dropId] = drop_; dropSellers[dropId] = msg.sender; emit DropCreated(msg.sender, dropId); _dropIdCounter.increment(); return dropId; } /// @dev Allows the seller to update drop start and end time. function updateDropTimeline( uint256 dropId_, uint64 notBefore_, uint64 deadline_ ) external { require(dropSellers[dropId_] == msg.sender, "gacha: unauthorized"); drops[dropId_].notBefore = notBefore_; drops[dropId_].deadline = deadline_; emit DropUpdated(msg.sender, dropId_); } /// @notice Allow anyone to remove a token that has been transferred away by the seller. function removeDropToken(uint256 dropId_, uint256 tokenIdx_) external { Drop storage drop = drops[dropId_]; require(drop.tokenAddress != address(0), "gacha: not found"); uint256 tokenId = drop.tokenIds[tokenIdx_]; // Remove the token first, run the check after drop.tokenIds[tokenIdx_] = drop.tokenIds[drop.tokenIds.length - 1]; drop.tokenIds.pop(); require(IERC721(drop.tokenAddress).ownerOf(tokenId) != dropSellers[dropId_], "gacha: token still with seller"); emit DropUpdated(msg.sender, dropId_); } function deleteDrop(uint256 dropId_) external { require(dropSellers[dropId_] == msg.sender || owner() == msg.sender, "gacha: unauthorized"); delete drops[dropId_]; emit DropUpdated(msg.sender, dropId_); } /// @notice Returns the next drop ID function nextDropId() public view returns (uint256) { return _dropIdCounter.current(); } function peek(uint256 dropId) public view returns (Drop memory) { return drops[dropId]; } /// @notice Buyer's interface, delivers to the caller function buy(uint256 dropId_) external payable whenNotPaused nonReentrant { _buy(dropId_, msg.sender); } /// @notice Buyer's interface, delivers to a specified address function buy(uint256 dropId_, address deliverTo_) external payable whenNotPaused nonReentrant { _buy(dropId_, deliverTo_); } function _buy(uint256 dropId_, address deliverTo_) private { // CHECKS Drop storage drop = drops[dropId_]; require(drop.tokenAddress != address(0), "gacha: not found"); require(drop.tokenIds.length > 0, "gacha: sold out"); require(drop.notBefore <= block.timestamp, "gacha: auction not yet started"); require(drop.deadline == 0 || drop.deadline >= block.timestamp, "gacha: auction already ended"); require(msg.value == drop.price, "gacha: incorrect amount sent"); // EFFECTS // Select token at (semi-)random uint256 tokenIdx = uint256(keccak256(abi.encodePacked(block.timestamp))) % drop.tokenIds.length; uint256 tokenId = drop.tokenIds[tokenIdx]; // Remove the token from the drop tokens list drop.tokenIds[tokenIdx] = drop.tokenIds[drop.tokenIds.length - 1]; drop.tokenIds.pop(); address paymentReceiver = drop.paymentReceiver != address(0) ? drop.paymentReceiver : dropSellers[dropId_]; ( uint256 auctionFeeAmount, address royaltyReceiver, uint256 royaltyAmount, uint256 sellerShare ) = _getProceedsDistribution(paymentReceiver, drop.tokenAddress, tokenId, drop.price); // INTERACTIONS // Transfer the token and ensure delivery of the token IERC721(drop.tokenAddress).safeTransferFrom(dropSellers[dropId_], deliverTo_, tokenId); require(IERC721(drop.tokenAddress).ownerOf(tokenId) == deliverTo_, "gacha: token transfer failed"); // ensure delivery bool paymentSent; // Ensure delivery of the payment // solhint-disable-next-line avoid-low-level-calls (paymentSent, ) = paymentReceiver.call{value: sellerShare}(""); require(paymentSent, "gacha: seller share transfer failed"); // Pay out the royalty if (royaltyAmount > 0 && royaltyReceiver != address(0)) { // solhint-disable-next-line avoid-low-level-calls (paymentSent, ) = royaltyReceiver.call{value: royaltyAmount}(""); require(paymentSent, "gacha: royalty payment failed"); } // Transfer the auction fee if (auctionFeeAmount > 0 && _auctionFeeRecipient != address(0)) { // solhint-disable-next-line avoid-low-level-calls (paymentSent, ) = _auctionFeeRecipient.call{value: auctionFeeAmount}(""); require(paymentSent, "gacha: auction fee transfer failed"); } emit Sale(dropId_, tokenId, msg.sender); // Clean up the drop after all items have been sold if (drop.tokenIds.length == 0) { delete drops[dropId_]; } } function _getProceedsDistribution( address paymentReceiver_, address tokenAddress_, uint256 tokenId_, uint256 price_ ) private view returns ( uint256 auctionFeeAmount, address royaltyReceiver, uint256 royaltyAmount, uint256 sellerShare ) { // Auction fee auctionFeeAmount = (price_ * _auctionFeeBps) / 10000; // EIP-2981 royalty split (royaltyReceiver, royaltyAmount) = _getRoyaltyInfo(tokenAddress_, tokenId_, price_ - auctionFeeAmount); // No royalty address, or royalty goes to the seller if (royaltyReceiver == address(0) || royaltyReceiver == paymentReceiver_) { royaltyAmount = 0; } // Seller's share sellerShare = price_ - (auctionFeeAmount + royaltyAmount); // Internal consistency check assert(sellerShare + auctionFeeAmount + royaltyAmount <= price_); } function _getRoyaltyInfo( address tokenAddress_, uint256 tokenId_, uint256 price_ ) private view returns (address, uint256) { try IERC2981(tokenAddress_).royaltyInfo(tokenId_, price_) returns ( address royaltyReceiver, uint256 royaltyAmount ) { return (royaltyReceiver, royaltyAmount); } catch (bytes memory reason) { // EIP 2981's `royaltyInfo()` function is not implemented // treatment the same as here: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.1/contracts/token/ERC721/ERC721.sol#L379 if (reason.length == 0) { return (address(0), 0); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } /// /// @dev Auction fee setters and getters /// function auctionFeeBps() public view returns (uint256) { return _auctionFeeBps; } function setAuctionFeeBps(uint256 newAuctionFeeBps_) public onlyOwner { _auctionFeeBps = newAuctionFeeBps_; } function auctionFeeRecipient() public view returns (address) { return _auctionFeeRecipient; } function setAuctionFeeRecipient(address auctionFeeRecipient_) public onlyOwner { _auctionFeeRecipient = auctionFeeRecipient_; } /// @dev Allows the owner to withdraw any leftover funds function withdraw(address payable account_, uint256 amount_) public nonReentrant onlyOwner { // solhint-disable-next-line avoid-low-level-calls (bool paymentSent, ) = account_.call{value: amount_}(""); require(paymentSent, "gacha: withdrawal failed"); } /// /// @dev The following functions relate to pausing of the contract /// function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// /// @dev Interface for EIP-2981: NFT Royalty Standard /// interface IERC2981 is IERC165 { /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param tokenId_ - the NFT asset queried for royalty information * @param salePrice_ - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 tokenId_, uint256 salePrice_) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/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); }
Allows the seller to update drop start and end time.
function updateDropTimeline( uint256 dropId_, uint64 notBefore_, uint64 deadline_ ) external { require(dropSellers[dropId_] == msg.sender, "gacha: unauthorized"); drops[dropId_].notBefore = notBefore_; drops[dropId_].deadline = deadline_; emit DropUpdated(msg.sender, dropId_); }
1,173,575
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Ownable.sol'; import './ReentrancyGuard.sol'; import './SafeMath.sol'; import './SafeERC20.sol'; import './IERC20.sol'; contract SyrupPool is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The address of the smart chef factory address public POOL_FACTORY; // Whether a limit is set for users bool public hasUserLimit; // Whether it is initialized bool public isInitialized; // Accrued token per share uint256 public accTokenPerShare; // The block number when CAKE mining ends. uint256 public bonusEndBlock; // The block number when CAKE mining starts. uint256 public startBlock; // The block number of the last pool update uint256 public lastRewardBlock; uint256 public totalStaked; // The pool limit (0 if none) uint256 public poolLimitPerUser; // CAKE tokens created per block. uint256 public rewardPerBlock; // The precision factor uint256 public PRECISION_FACTOR; // The reward token IERC20 public rewardToken; // The staked token IERC20 public stakedToken; // Info of each user that stakes tokens (stakedToken) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // How many staked tokens the user has provided uint256 rewardDebt; // Reward debt } event AdminTokenRecovery(address tokenRecovered, uint256 amount); event Deposit(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock); event NewRewardPerBlock(uint256 rewardPerBlock); event NewPoolLimit(uint256 poolLimitPerUser); event RewardsStop(uint256 blockNumber); event RewardPaid(address indexed user, uint256 reward); event Withdraw(address indexed user, uint256 amount); constructor() { POOL_FACTORY = _msgSender(); } function initialize( IERC20 _stakedToken, IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, address _admin) external onlyOwner { require(!isInitialized, "Already initialized"); require(_msgSender() == POOL_FACTORY, "Not Pool factory"); uint256 decimalsRewardToken = uint256(_rewardToken.decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); // Make this contract initialized isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; if (_poolLimitPerUser > 0) { hasUserLimit = true; poolLimitPerUser = _poolLimitPerUser; } // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken))); // Transfer ownership to the admin address who becomes owner of the contract transferOwnership(_admin); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(stakedToken), "Cannot be staked token"); require(_tokenAddress != address(rewardToken), "Cannot be reward token"); IERC20(_tokenAddress).safeTransfer(address(_msgSender()), _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /* * @notice Withdraw staked tokens without caring about rewards rewards * @dev Needs to be for emergency. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[_msgSender()]; uint256 amountToTransfer = user.amount; user.amount = 0; user.rewardDebt = 0; if (amountToTransfer > 0) { stakedToken.safeTransfer(address(_msgSender()), amountToTransfer); totalStaked = totalStaked.sub(amountToTransfer); } emit EmergencyWithdraw(_msgSender(), user.amount); } /* * @notice Stop rewards * @dev Only callable by owner. Needs to be for emergency. */ function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { rewardToken.safeTransfer(address(_msgSender()), _amount); } /* * @notice Stop rewards * @dev Only callable by owner */ function stopReward() external onlyOwner { bonusEndBlock = block.number; } /* * @notice Update pool limit per user * @dev Only callable by owner. * @param _hasUserLimit: whether the limit remains forced * @param _poolLimitPerUser: new pool limit per user */ function updatePoolLimitPerUser(bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner { if (_hasUserLimit) { require(_poolLimitPerUser > poolLimitPerUser, "New limit must be higher"); poolLimitPerUser = _poolLimitPerUser; } else { hasUserLimit = _hasUserLimit; poolLimitPerUser = 0; } emit NewPoolLimit(poolLimitPerUser); } /* * @notice Update reward per block * @dev Only callable by owner. * @param _rewardPerBlock: the reward per block */ function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { require(block.number < startBlock || startBlock == 0, "Pool has started"); rewardPerBlock = _rewardPerBlock; emit NewRewardPerBlock(_rewardPerBlock); } /** * @notice It allows the admin to update start and end blocks * @dev This function is only callable by owner. * @param _startBlock: the new start block * @param _bonusEndBlock: the new end block */ function updateStartAndEndBlocks(uint256 _startBlock, uint256 _bonusEndBlock) external onlyOwner { require(block.number < startBlock || startBlock == 0, "Pool has started"); require(_startBlock < _bonusEndBlock, "New startBlock must be lower than new endBlock"); require(block.number < _startBlock, "New startBlock must be higher than current block"); startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock); } /* * @notice Deposit staked tokens and collect reward tokens (if any) * @param _amount: amount to withdraw (in rewardToken) */ function deposit(uint256 _amount) external nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; if (hasUserLimit) { require(_amount.add(user.amount) <= poolLimitPerUser, "User amount above limit"); } _updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); } } if (_amount > 0) { user.amount = user.amount.add(_amount); totalStaked = totalStaked.add(_amount); stakedToken.safeTransferFrom(address(_msgSender()), address(this), _amount); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); emit Deposit(_msgSender(), _amount); } /* * @notice Withdraw staked tokens and collect reward tokens * @param _amount: amount to withdraw (in rewardToken) */ function withdraw(uint256 _amount) external nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; require(user.amount >= _amount, "Amount to withdraw too high"); _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (_amount > 0) { user.amount = user.amount.sub(_amount); totalStaked = totalStaked.sub(_amount); stakedToken.safeTransfer(address(_msgSender()), _amount); emit Withdraw(_msgSender(), _amount); } if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); emit RewardPaid(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); } function getReward() public nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); emit RewardPaid(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); } /* * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(address _user) external view returns (uint256) { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_user]; uint256 stakedTokenSupply = totalStaked; if (block.number > lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } /* * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } uint256 stakedTokenSupply = totalStaked; if (stakedTokenSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(rewardPerBlock); accTokenPerShare = accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); lastRewardBlock = block.number; } function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from); } if (_from >= bonusEndBlock) { return 0; } return bonusEndBlock.sub(_from); } }
Stop rewards Only callable by owner. Needs to be for emergency./
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { rewardToken.safeTransfer(address(_msgSender()), _amount); }
12,614,795
./partial_match/42220/0x56E44A9f86C2e3a53e816335cBE6deaE440b0856/sources/WitnetPriceFeedBypass.sol
Extract bytes array from buffer starting from current cursor. buffer An instance of `Buffer`. length How many bytes to peek from the Buffer. solium-disable-next-line security/no-assign-params
function peek( WitnetBuffer.Buffer memory buffer, uint length ) internal pure withinRange(length, buffer.data.length - buffer.cursor) returns (bytes memory) { return peek( buffer, buffer.cursor, length ); }
3,498,187
pragma solidity ^0.4.24; /** * @title -FoMo-3Dx beta * * WARNING: THIS PRODUCT IS HIGHLY ADDICTIVE. IF YOU HAVE AN ADDICTIVE NATURE. DO NOT PLAY. */ //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 devAmount, uint256 genAmount, uint256 potAmount ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 devAmount, uint256 genAmount ); // (fomo3dx only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 devAmount, uint256 genAmount ); // (fomo3dx only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 devAmount, uint256 genAmount ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents {} contract F3Dx is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; address constant private AwardPool = 0xb14D7b0ec631Daf0cF02d69860974df04987a9f8; address constant private DeveloperRewards = 0xb14D7b0ec631Daf0cF02d69860974df04987a9f8; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xdAc532cA5598Ee19a2dfC1244c7608C766c6C415); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMo3D X"; string constant public symbol = "F3Dx"; uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 8 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** 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 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data //**************** // FEE DATA //**************** F3Ddatasets.KeyFee public fees_; // fee distribution by holder F3Ddatasets.PotSplit public potSplit_; // fees pot split distribution //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Key allocation percentages // F3Dx + (Pot, Share, Developer) fees_ = F3Ddatasets.KeyFee(50,10); //40% to pot, 50% to key holder, 10% to dev reward // Pot allocation percentages // (WIN, DEV) potSplit_ = F3Ddatasets.PotSplit(40,10); //40% to offcial then transfer to winner, 10% to dev reward, 50% to official } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet."); _; } /** * @dev prevents contracts from interacting with fomo3dx */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, _eventData_); } /** * @dev converts all incoming ethereum to keys. */ function buyXid() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, _eventData_); } function buyXaddr() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, _eventData_); } function buyXname() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // reload core reLoadCore(_pID, _eth, _eventData_); } function reLoadXaddr(uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // reload core reLoadCore(_pID, _eth, _eventData_); } function reLoadXname(uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // reload core reLoadCore(_pID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.devAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * - 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 * @param _nameString players desired name * @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, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; bool _isNewPlayer = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _paid, now); } function registerNameXaddr(string _nameString, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; bool _isNewPlayer = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _paid, now); } function registerNameXname(string _nameString, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; bool _isNewPlayer = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you&#39;ll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ) ); // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)) ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(50)).div(100)).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return player ID in lead * @return current player in leads address * @return current player in leads name */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].plyr * 10), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name //8 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyrRnds_[_pID][_rID].eth //5 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.devAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.devAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); // distribute eth _eventData_ = distributeExternal(_eth, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3dx if (_pID == 0) { // grab their player ID, name, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player&#39;s last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player uint256 _winPID = round_[_rID].plyr; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share and developer rewards uint256 _win = (_pot.mul(potSplit_.win)).div(100); // 40% to winner uint256 _dev = (_pot.mul(potSplit_.dev)).div(100); // 10% to dev rewards _pot = (_pot.sub(_win)).sub(_dev); // calc remaining amount to pot // pay out to official then transfer to winner AwardPool.transfer(_win); // pay our developer DeveloperRewards.transfer(_dev); // ended this pot AwardPool.transfer(_pot); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.potAmount = _pot; _eventData_.devAmount = _dev; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_); return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev distributes eth based on fees to dev */ function distributeExternal(uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 10% out to developer rewards uint256 _dev = (_eth.mul(fees_.dev)).div(100); // transfer to developer rewards contract DeveloperRewards.transfer(_dev); // set up event data _eventData_.devAmount = _dev.add(_eventData_.devAmount); return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_.gen)).div(100); // update eth balance (eth = eth - dev share) _eth = _eth.sub((_eth.mul(fees_.dev)).div(100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, 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 were 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 rounds mask, my shares, and how much i&#39;ve already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // 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); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx&#39;s */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.devAmount, _eventData_.genAmount, _eventData_.potAmount ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team can activate require(msg.sender == 0x4a1061afb0af7d9f6c2d545ada068da68052c060, "only team can activate"); // can only be ran once require(activated_ == false, "fomo3dx already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 devAmount; // amount distributed to dev uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 lrnd; // last round played } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player 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 } struct KeyFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 dev; // % of buy in thats paid to develper } struct PotSplit { uint256 win; // % of pot thats paid to winner of current round uint256 dev; // % of pot thats paid to developer } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== 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()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, bool _all) external payable returns(bool); function registerNameXaddrFromDapp(address _addr, bytes32 _name, bool _all) external payable returns(bool); function registerNameXnameFromDapp(address _addr, bytes32 _name, bool _all) external payable returns(bool); } /** * @title -Name Filter- beta */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath * @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 */ 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) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, 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); } } /** * @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; } }
set up our tx event data fetch player ID reload core
function reLoadXaddr(uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; reLoadCore(_pID, _eth, _eventData_); }
15,035,075
// File: contracts\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts\IERC165.sol pragma solidity ^0.5.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\IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {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 owner, 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.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {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.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts\Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts\Counters.sol pragma solidity ^0.5.0; /** * @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.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: contracts\ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ 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_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 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; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {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 { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _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), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to 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 tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, 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 tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {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); } } } // File: contracts\IERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: contracts\ERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; /* * 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 Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @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 { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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.sub(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } // File: contracts\IERC721Metadata.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts\ERC721Metadata.sol pragma solidity ^0.5.0; 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(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: contracts\ERC721Full.sol pragma solidity ^0.5.0; /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } // File: contracts\Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts\MinterRole.sol pragma solidity ^0.5.0; 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); } } // File: contracts\ERC721MetadataMintable.sol pragma solidity ^0.5.0; /** * @title ERC721MetadataMintable * @dev ERC721 minting logic with metadata. */ contract ERC721MetadataMintable is ERC721, ERC721Metadata, MinterRole { /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens. * @param tokenId The token id to mint. * @param tokenURI The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; } } // File: contracts\SmirriauNFTContracts.sol //Smirriau NFT Token ERC 721 & Marketplace for sale and minting //2021 WikiCode - José Miguel López Salvador pragma solidity ^0.5.0; //Import the OpenZeppeling contracts //Smirriau Token //This is the ERC721 personalized token for Smirriau NFT //This contract has a limit of 5000 tokens contract SmirriauToken is ERC721Full, ERC721MetadataMintable { //Set a constant with the limit of minting uint256 constant maxCounter = 5000; //The constructor to set the name and symbol constructor () public ERC721Full("SmirriauNft","SMR") { } //This function is used to mint a token cheking first the limit of the total supply. function createSmirriau (address nftOwner, uint256 tokenId, string memory tokenURI) public returns(bool) { require (totalSupply()<maxCounter,"Max minted SMR reached"); assert(mintWithTokenURI(nftOwner, tokenId, tokenURI)); return true; } } //Smirriau Market //This contract will be a minter of Smirriau Token and it is used for sell the original tokens in the website. contract SmirriauMarket { using SafeMath for uint256; //The token contract SmirriauToken public smirriauToken; //The address which will receive the payments address payable private destEthers; //A total collected uint256 public totalCollected; //The token price uint256 public tokenPrice; //The controller of this contract address public controller; //A list of minted index mapping (uint256 => bool) public minted; //Another list of minted index uint256[] public mintedList; //Constructor constructor () public { //Set the total collected in 0 totalCollected = 0; //Set the publisher of the contract as a controller controller = msg.sender; } //The modifier for only controller modifier onlyController() { require (msg.sender == controller, "Must be controller"); _; } //This function check if the token is available or not function isTokenAvailableByIndex(uint256 index) public view returns(bool){ bool available = true; if (minted[index]==true){ available = false; } return available; } //Return all the minted indexes function getMintedList() public view returns(uint256 [] memory){ return mintedList; } //Get the balance of this contract function getBalance() public onlyController view returns(uint256) { return address(this).balance; } //Withdraw if there is some ETH in the contract function withdrawBalance() public onlyController { require(address(this).balance > 0, "Balance 0"); destEthers.transfer(address(this).balance); } //Initialize the market with the information of the token address, price and address for payments. function initialize (address _token, address payable _destEth, uint256 _tokenPrice) public onlyController { address tokenAddress = address(smirriauToken); require(tokenAddress==0x0000000000000000000000000000000000000000, "The smirriauToken already exists"); smirriauToken = SmirriauToken(_token); require(smirriauToken.totalSupply() == 0, "There are some tokens in the contract"); require(smirriauToken.isMinter(address(this))== true, "This address has not the correct roles"); tokenPrice = _tokenPrice; destEthers = _destEth; } //Change the address for payments function setDestEthers (address payable _destEth) public onlyController { destEthers = _destEth; } //Get the address for payments function getDestEthers () public onlyController view returns(address) { return destEthers; } //This is used to mint a new Smirriau by index and its tokenURI function buyNewSmirriau(string memory tokenURI, uint256 _index) public payable returns(uint256) { uint256 buyPrice = tokenPrice; //50% Frst 100 NFTs if(totalCollected<100) { buyPrice = tokenPrice/2; } require(msg.value >= buyPrice, "Not enouth ETH to buy"); require(isTokenAvailableByIndex(_index) == true , "Token not available"); address buyer = msg.sender; // uint256 index = tokenIndex++; assert(smirriauToken.createSmirriau(buyer, _index, tokenURI)); destEthers.transfer(buyPrice); if (msg.value>buyPrice) { msg.sender.transfer(msg.value.sub(buyPrice)); } minted[_index] = true; mintedList.push(_index); totalCollected++; return _index; } }
Function to mint tokens. to The address that will receive the minted tokens. tokenId The token id to mint. tokenURI The token URI of the minted token. return A boolean that indicates if the operation was successful./
function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; }
275,996
./full_match/4/0x7225cb7aFCD5FfE14c65891B082196634ED410f8/sources/contracts/PrimeNft.sol
Initializer function./
function initialize() public initializer { ERC721Upgradeable.__ERC721_init("Valor Prime NonFungibles", "VPT"); OwnableUpgradeable.__Ownable_init(); }
12,347,413
./full_match/80001/0x91B305F9370C90C0911C3e7Bf7e2ab7be76887d4/sources/KushoStaking.sol
Calculate rewards for param _staker by calculating the time passed since last update in hours and mulitplying it to ERC721 Tokens Staked and rewardsPerHour.
function calculateRewards(address _staker) internal view returns (uint256 _rewards) { return ((( ((block.timestamp - stakers[_staker].timeOfLastUpdate) * stakers[_staker].amountStaked) ) * rewardsPerHour) / 3600); }
5,702,485
pragma solidity ^0.4.24; // pragma experimental ABIEncoderV2; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library Helper { using SafeMath for uint256; function bytes32ToUint(bytes32 n) public pure returns (uint256) { return uint256(n); } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function stringToUint(string memory source) public pure returns (uint256) { return bytes32ToUint(stringToBytes32(source)); } function validUsername(string _username) public pure returns(bool) { bytes memory b = bytes(_username); // Im Raum [4, 18] if ((b.length < 4) || (b.length > 18)) return false; // Letzte Char != ' ' for(uint i; i<b.length; i++){ bytes1 char = b[i]; if( !(char >= 0x30 && char <= 0x39) && !(char >= 0x41 && char <= 0x5A) //A-Z ) return false; } if (b[0] >= 0x30 && b[0] <= 0x39) return false; return true; } } interface DAAInterface { function citizenMintToken(address _buyer, uint256 _buyPrice, int8 _is_win) external returns(uint256); function transfer(address _to, uint256 _value) external returns(bool); function transferFrom(address _from, address _to, uint256 _tokenAmount) external returns(bool); function balanceOf(address _from) external returns(uint256); function currentRoundDividend() external; function getDividendView(address _sender) external returns(uint256); function getDividendPull(address _sender, uint256 _value) external returns(uint256); function payOut(address _winner, uint256 _unit, uint256 _value, uint256 _valuebet) external; function getCitizenBalanceEth(address _sender) external returns(uint256); function totalSupplyByAddress(address _sender) external returns(uint256); } interface TicketInterface{ function getEarlyIncomePull(address _sender) external returns(uint256); function getEarlyIncomeView(address _sender, bool _current) external returns(uint256); function getEarlyIncomeByRound(address _buyer, uint256 _round) external returns(uint256); function currentRound() external returns(uint256); function ticketSumByAddress(address _sender) external returns(uint256); } contract CitizenStorage{ using SafeMath for uint256; address controller; modifier onlyCoreContract() { require(msg.sender == controller, "admin required"); _; } mapping (address => uint256) public citizenWinIncome; mapping (address => uint256) public citizenGameWinIncome; mapping (address => uint256) public citizenWithdrawed; function addWinIncome(address _citizen, uint256 _value) public onlyCoreContract() { citizenWinIncome[_citizen] = _value.add(citizenWinIncome[_citizen]); citizenWithdrawed[_citizen] = citizenWithdrawed[_citizen].add(_value); } function addGameWinIncome(address _citizen, uint256 _value, bool _enough) public onlyCoreContract() { citizenGameWinIncome[_citizen] = _value.add(citizenGameWinIncome[_citizen]); if (_enough){ citizenWithdrawed[_citizen] = citizenWithdrawed[_citizen].add(_value); } } function pushCitizenWithdrawed(address _sender, uint256 _value) public onlyCoreContract(){ citizenWithdrawed[_sender] = citizenWithdrawed[_sender].add(_value); } constructor (address _contract) public { require(controller== 0x0, "require setup"); controller = _contract; } } contract Citizen{ using SafeMath for uint256; // event Register(uint256 id, uint256 username, address indexed citizen, address indexed ref, // uint256 ticket, uint256 ticketSpend, uint256 totalGameSpend, uint256 totalMined, // uint256 dateJoin, uint256 totalWithdraw); event Register(uint256 id, uint256 username, address indexed citizen, address indexed ref, uint256 ticketSpend, uint256 totalGameSpend, uint256 dateJoin); modifier onlyAdmin() { require(msg.sender == devTeam1, "admin required"); _; } modifier onlyCoreContract() { require(isCoreContract[msg.sender], "admin required"); _; } modifier notRegistered(){ require(!isCitizen[msg.sender], "already exist"); _; } modifier registered(){ require(isCitizen[msg.sender], "must be a citizen"); _; } uint8[10] public TICKET_LEVEL_REF = [uint8(60),40,20,10,10,10,5,5,5,5];// 3 demical uint8[10] public GAME_LEVEL_REF = [uint8(5),2,1,1,1,1,1,1,1,1];// 3 demical struct Profile{ uint256 id; uint256 username; address ref; mapping(uint => address[]) refTo; mapping(address => uint256) payOut; uint256 totalChild; uint256 treeLevel; uint256 citizenBalanceEth; uint256 citizenBalanceEthBackup; uint256 citizenTicketSpend; uint256 citizenGameEthSpend; uint256 citizenGameTokenSpend; uint256 citizenEarlyIncomeRevenue; uint256 citizenTicketRevenue; uint256 citizenGameEthRevenue; uint256 citizenGameTokenRevenue; } mapping (address => uint256) public citizenEthDividend; address[21] public mostTotalSpender; mapping (address => uint256) public mostTotalSpenderId; mapping (address => mapping(uint256 => uint256)) public payOutByLevel; mapping (address => Profile) public citizen; mapping (address => bool) public isCitizen; mapping (uint256 => address) public idAddress; mapping (uint256 => address) public usernameAddress; mapping (uint256 => address[]) public levelCitizen; address devTeam1; address devTeam2; address devTeam3; address devTeam4; uint256 public citizenNr; uint256 lastLevel; uint256 earlyIncomeBalanceEth; DAAInterface public DAAContract; TicketInterface public TicketContract; CitizenStorage public CitizenStorageContract; mapping (address => bool) public isCoreContract; uint256 public coreContractSum; address[] public coreContracts; constructor (address[4] _devTeam) public { devTeam1 = _devTeam[0]; devTeam2 = _devTeam[1]; devTeam3 = _devTeam[2]; devTeam4 = _devTeam[3]; // first citizen is the development team citizenNr = 1; idAddress[1] = devTeam3; isCitizen[devTeam3] = true; //root => self ref citizen[devTeam3].ref = devTeam3; // username rules bypass uint256 _username = Helper.stringToUint("GLOBAL"); citizen[devTeam3].username = _username; usernameAddress[_username] = devTeam3; citizen[devTeam3].id = 1; citizen[devTeam3].treeLevel = 1; levelCitizen[1].push(devTeam3); lastLevel = 1; } // DAAContract, TicketContract, CitizenContract, CitizenStorage function joinNetwork(address[4] _contract) public { require(address(DAAContract) == 0x0,"already setup"); DAAContract = DAAInterface(_contract[0]); TicketContract = TicketInterface(_contract[1]); CitizenStorageContract = CitizenStorage(_contract[3]); for(uint256 i =0; i<3; i++){ isCoreContract[_contract[i]]=true; coreContracts.push(_contract[i]); } coreContractSum = 3; } function updateTotalChild(address _address) private { address _member = _address; while(_member != devTeam3) { _member = getRef(_member); citizen[_member].totalChild ++; } } function addCoreContract(address _address) public // [dev1] onlyAdmin() { require(_address!=0x0,"Invalid address"); isCoreContract[_address] = true; coreContracts.push(_address); coreContractSum+=1; } function updateRefTo(address _address) private { address _member = _address; uint256 level =1; while (_member != devTeam3 && level<11){ _member = getRef(_member); citizen[_member].refTo[level].push(_address); level = level+1; } } function register(string _sUsername, address _ref) public notRegistered() { require(Helper.validUsername(_sUsername), "invalid username"); address sender = msg.sender; uint256 _username = Helper.stringToUint(_sUsername); require(usernameAddress[_username] == 0x0, "username already exist"); usernameAddress[_username] = sender; //ref must be a citizen, else ref = devTeam address validRef = isCitizen[_ref] ? _ref : devTeam3; //Welcome new Citizen isCitizen[sender] = true; citizen[sender].username = _username; citizen[sender].ref = validRef; citizenNr++; idAddress[citizenNr] = sender; citizen[sender].id = citizenNr; uint256 refLevel = citizen[validRef].treeLevel; if (refLevel == lastLevel) lastLevel++; citizen[sender].treeLevel = refLevel + 1; levelCitizen[refLevel + 1].push(sender); //add child updateRefTo(sender); updateTotalChild(sender); emit Register(citizenNr,_username, sender, validRef, citizen[sender].citizenTicketSpend, citizen[sender].citizenGameEthSpend, now); } // function updateUsername(string _sNewUsername) // public // registered() // { // require(Helper.validUsername(_sNewUsername), "invalid username"); // address sender = msg.sender; // uint256 _newUsername = Helper.stringToUint(_sNewUsername); // require(usernameAddress[_newUsername] == 0x0, "username already exist"); // uint256 _oldUsername = citizen[sender].username; // citizen[sender].username = _newUsername; // usernameAddress[_oldUsername] = 0x0; // usernameAddress[_newUsername] = sender; // } function getRef(address _address) public view returns (address) { return citizen[_address].ref == 0x0 ? devTeam3 : citizen[_address].ref; } function getUsername(address _address) public view returns (uint256) { return citizen[_address].username; } function isDev() public view returns(bool){ if (msg.sender == devTeam1) return true; return false; } function getAddressById(uint256 _id) public view returns (address) { return idAddress[_id]; } function getAddressByUserName(string _username) public view returns (address) { return usernameAddress[Helper.stringToUint(_username)]; } function pushTicketRefIncome(address _sender) public payable onlyCoreContract() { uint256 _amount = msg.value; // 17% _amount = _amount.div(170); address sender = _sender; address ref = getRef(sender); uint256 money; uint8 level; for (level=0; level<10; level++){ money = _amount.mul(TICKET_LEVEL_REF[level]); citizen[ref].citizenBalanceEth = money.add(citizen[ref].citizenBalanceEth); citizen[ref].citizenTicketRevenue = money.add(citizen[ref].citizenTicketRevenue); citizen[ref].payOut[_sender] = money.add(citizen[ref].payOut[_sender]); payOutByLevel[ref][level+1] = money.add(payOutByLevel[ref][level+1]); sender = ref; ref = getRef(sender); } } function pushGametRefIncome(address _sender) public payable onlyCoreContract() { uint256 _amount = msg.value; // 1.5% _amount = _amount.div(15); address sender = _sender; address ref = getRef(sender); uint256 level; uint256 money; uint256 forDaa; for (level=0; level<10; level++){ forDaa=0; money = _amount.mul(GAME_LEVEL_REF[level]); if (citizen[ref].citizenGameEthRevenue<citizen[ref].citizenGameEthSpend.div(10)){ if (citizen[ref].citizenGameEthRevenue+money>citizen[ref].citizenGameEthSpend.div(10)){ forDaa = citizen[ref].citizenGameEthRevenue+money-citizen[ref].citizenGameEthSpend.div(10); money = money.sub(forDaa); } } else { forDaa = money; money = 0; } citizen[ref].citizenBalanceEth = money.add(citizen[ref].citizenBalanceEth); citizen[ref].citizenGameEthRevenue = money.add(citizen[ref].citizenGameEthRevenue); citizen[ref].payOut[_sender] = money.add(citizen[ref].payOut[_sender]); payOutByLevel[ref][level+1] = money.add(payOutByLevel[ref][level+1]); citizen[devTeam3].citizenBalanceEth = forDaa.add(citizen[devTeam3].citizenBalanceEth); citizen[devTeam3].citizenGameEthRevenue = forDaa.add(citizen[devTeam3].citizenGameEthRevenue); sender = ref; ref = getRef(sender); } } function pushGametRefIncomeToken(address _sender, uint256 _amount) public payable onlyCoreContract() { _amount = _amount.div(15); address sender = _sender; address ref = getRef(sender); uint256 level; uint256 money; uint256 forDaa; for (level=0; level<10; level++){ forDaa=0; money = _amount.mul(GAME_LEVEL_REF[level]); if (citizen[ref].citizenGameTokenRevenue<citizen[ref].citizenGameTokenSpend.div(10)){ if (citizen[ref].citizenGameTokenRevenue+money>citizen[ref].citizenGameTokenSpend.div(10)){ forDaa = citizen[ref].citizenGameTokenRevenue+money-citizen[ref].citizenGameTokenSpend.div(10); money = money.sub(forDaa); } } else { forDaa = money; money = 0; } DAAContract.payOut(ref,1,money,0); citizen[ref].citizenGameTokenRevenue=money.add(citizen[ref].citizenGameTokenRevenue); DAAContract.payOut(devTeam3,1,forDaa,0); citizen[devTeam3].citizenGameTokenRevenue = forDaa.add(citizen[devTeam3].citizenGameTokenRevenue); sender = ref; ref = getRef(sender); } } function pushEarlyIncome() public payable{ uint256 _value = msg.value; earlyIncomeBalanceEth = earlyIncomeBalanceEth.add(_value); } function sortMostSpend(address _citizen) private { uint256 citizen_spender = getTotalSpend(_citizen); uint256 i=1; while (i<21) { if (mostTotalSpender[i]==0x0||(mostTotalSpender[i]!=0x0&&getTotalSpend(mostTotalSpender[i])<citizen_spender)){ if (mostTotalSpenderId[_citizen]!=0&&mostTotalSpenderId[_citizen]<i){ break; } if (mostTotalSpenderId[_citizen]!=0){ mostTotalSpender[mostTotalSpenderId[_citizen]]=0x0; } address temp1 = mostTotalSpender[i]; address temp2; uint256 j=i+1; while (j<21&&temp1!=0x0){ temp2 = mostTotalSpender[j]; mostTotalSpender[j]=temp1; mostTotalSpenderId[temp1]=j; temp1 = temp2; j++; } mostTotalSpender[i]=_citizen; mostTotalSpenderId[_citizen]=i; break; } i++; } } function addTicketEthSpend(address _citizen, uint256 _value) onlyCoreContract() public { citizen[_citizen].citizenTicketSpend = citizen[_citizen].citizenTicketSpend.add(_value); DAAContract.citizenMintToken(_citizen,_value,0);// buy ticket 0, win 1, lose -1; sortMostSpend(_citizen); } // Game spend function addGameEthSpendWin(address _citizen, uint256 _value, uint256 _valuewin, bool _enough) onlyCoreContract() public { citizen[_citizen].citizenGameEthSpend = citizen[_citizen].citizenGameEthSpend.add(_value); // DAAContract.citizenMintToken(_citizen,_value,1);// buy ticket 0, win 1, lose -1; CitizenStorageContract.addGameWinIncome(_citizen, _valuewin, _enough); sortMostSpend(_citizen); } function addGameEthSpendLose(address _citizen, uint256 _value) onlyCoreContract() public { citizen[_citizen].citizenGameEthSpend = citizen[_citizen].citizenGameEthSpend.add(_value); DAAContract.citizenMintToken(_citizen,_value,-1);// buy ticket 0, win 1, lose -1; sortMostSpend(_citizen); } function addGameTokenSpend(address _citizen, uint256 _value) onlyCoreContract() public { citizen[_citizen].citizenGameTokenSpend = citizen[_citizen].citizenGameTokenSpend.add(_value); } function withdrawEth() public registered() { address _sender = msg.sender; uint256 _earlyIncome = TicketContract.getEarlyIncomePull(_sender); uint256 _devidend = DAAContract.getDividendView(msg.sender); uint256 _citizenBalanceEth = citizen[_sender].citizenBalanceEth; uint256 _total = _earlyIncome.add(_devidend).add(_citizenBalanceEth).add(DAAContract.getCitizenBalanceEth(_sender)); require(_total>0,"Balance none"); CitizenStorageContract.pushCitizenWithdrawed(_sender,_total); DAAContract.getDividendPull(_sender,_citizenBalanceEth+_earlyIncome); _sender.transfer(_citizenBalanceEth+_earlyIncome); citizen[_sender].citizenBalanceEthBackup = citizen[_sender].citizenBalanceEthBackup.add(_citizenBalanceEth).add(_earlyIncome).add(_devidend); citizen[_sender].citizenEarlyIncomeRevenue = citizen[_sender].citizenEarlyIncomeRevenue.add(_earlyIncome); citizenEthDividend[_sender] = citizenEthDividend[_sender].add(_devidend); earlyIncomeBalanceEth= earlyIncomeBalanceEth.sub(_earlyIncome); citizen[_sender].citizenBalanceEth = 0; } function addWinIncome(address _citizen, uint256 _value) onlyCoreContract() public { CitizenStorageContract.addWinIncome(_citizen, _value); } // function addGameWinIncome(address _citizen, uint256 _value, bool _enough) public { // CitizenStorageContract.addGameWinIncome(_citizen, _value, _enough); // } // function getInWallet() public view returns (uint256){ // uint256 _sum; // address _sender = msg.sender; // _sum = _sum.add(citizen[_sender].citizenBalanceEth); // _sum = _sum.add(TicketContract.getEarlyIncomeView(_sender)); // _sum = _sum.add(DAAContract.getDividendView(_sender)); // _sum = _sum.add(DAAContract.getCitizenBalanceEth(_sender)); // return _sum; // } function getTotalEth() public registered() view returns(uint256){ uint256 _sum; address _sender = msg.sender; _sum = _sum.add(citizen[_sender].citizenBalanceEth); _sum = _sum.add(citizen[_sender].citizenBalanceEthBackup); _sum = _sum.add(CitizenStorageContract.citizenWinIncome(_sender)); _sum = _sum.add(TicketContract.getEarlyIncomeView(_sender, false)); _sum = _sum.add(DAAContract.getDividendView(_sender)); return _sum; } function getTotalDividend(address _sender) public registered() view returns(uint256){ return citizenEthDividend[_sender].add(DAAContract.getDividendView(_sender)); } function getTotalEarlyIncome(address _sender) public registered() view returns(uint256){ uint256 _sum; _sum = citizen[_sender].citizenEarlyIncomeRevenue; _sum = _sum.add(TicketContract.getEarlyIncomeView(_sender, true)); return _sum; } function getTotalSpend(address _sender) public view returns(uint256){ return citizen[_sender].citizenGameEthSpend+citizen[_sender].citizenTicketSpend; } function getMemberByLevelToTal(uint256 _level) public view returns(uint256, uint256){ address _sender = msg.sender; return(citizen[_sender].refTo[_level].length,payOutByLevel[_sender][_level]); } function getMemberByLevel(uint256 _level, address _sender, uint256 _id) public view returns(address){ return citizen[_sender].refTo[_level][_id]; } function citizenPayForRef(address _citizen, address _ref) public view returns(uint256){ return citizen[_ref].payOut[_citizen]; } }
Game spend DAAContract.citizenMintToken(_citizen,_value,1); buy ticket 0, win 1, lose -1;
function addGameEthSpendWin(address _citizen, uint256 _value, uint256 _valuewin, bool _enough) onlyCoreContract() public { citizen[_citizen].citizenGameEthSpend = citizen[_citizen].citizenGameEthSpend.add(_value); CitizenStorageContract.addGameWinIncome(_citizen, _valuewin, _enough); sortMostSpend(_citizen); }
15,859,223
pragma solidity ^0.4.17; contract Authentic { address public manufacturer; address[] a = new address[](1); //Constructor to initialize manufacturer who deploy this contract function Authentic()public{ manufacturer=msg.sender; a.push(manufacturer); } // Structure to keep product details struct product{ string product_id; string product_name; string model; string brand; string owner; string owner_location; string manufacturer_name; address owner_address; } modifier restricted(){ require(ask_manufacturer_address()==msg.sender, "You are not authorized"); _; } //Map for mapping product id with product details mapping(string=>product) product_array; //Product add function only have access to manufacturer function addProduct(string _id,string p_name,string model_,string brand_,string owner_,string owner_loc,string m_name) public restricted returns(uint){ product current ; current.product_id = _id; current.product_name = p_name; current.model = model_; current.brand = brand_; current.owner = owner_; current.owner_location = owner_loc; current.owner_address=msg.sender; current.manufacturer_name = m_name; product_array[_id]=current; return 1; } //Change owner name function change_owner(address new_owner_address,string new_owner_name,string p_id,string new_owner_location)public returns (uint){ require(product_array[p_id].owner_address == msg.sender,"You are not owner of given product id"); product_array[p_id].owner_address= new_owner_address; product_array[p_id].owner= new_owner_name; product_array[p_id].owner_location= new_owner_location; return 1; } //Returns owner name function ask_owner_name(string _id) public view returns (string){ return(product_array[_id].owner); } //Returns caller address function ask_manufacturer_address() public view returns (address){ return(a[1]); } // function ask_len() public view returns (uint){ // return(a.length); // } //Returns owner location function ask_owner_location(string _id) public view returns (string){ return(product_array[_id].owner_location); } //Returns manufacturer name function ask_manufacturer_name(string _id) public view returns (string){ return(product_array[_id].manufacturer_name); } //Returns Poduct name function ask_product_name(string _id) public view returns (string){ return(product_array[_id].product_name); } //Returns Poduct id function ask_product_id(string _id) public view returns (string){ return(product_array[_id].product_id); } function ask_model(string _id) public view returns (string){ return(product_array[_id].model); } function ask_brand(string _id) public view returns (string){ return(product_array[_id].brand); } }
Returns owner location
function ask_owner_location(string _id) public view returns (string){ return(product_array[_id].owner_location); }
1,004,532
//Address: 0x1d9ca3546b84d3103b551c7d5006e4db172e06e6 //Contract name: Arbitrator //Balance: 0 Ether //Verification Date: 3/21/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract RealityCheckAPI { function setQuestionFee(uint256 fee) public; function finalizeByArbitrator(bytes32 question_id, bytes32 answer) public; function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer) public; function notifyOfArbitrationRequest(bytes32 question_id, address requester) public; function isFinalized(bytes32 question_id) public returns (bool); function withdraw() public; } contract Arbitrator is Owned { mapping(bytes32 => uint256) public arbitration_bounties; uint256 dispute_fee; mapping(bytes32 => uint256) custom_dispute_fees; event LogRequestArbitration( bytes32 indexed question_id, uint256 fee_paid, address requester, uint256 remaining ); event LogSetQuestionFee( uint256 fee ); event LogSetDisputeFee( uint256 fee ); event LogSetCustomDisputeFee( bytes32 indexed question_id, uint256 fee ); /// @notice Constructor. Sets the deploying address as owner. function Arbitrator() public { owner = msg.sender; } /// @notice Set the default fee /// @param fee The default fee amount function setDisputeFee(uint256 fee) onlyOwner public { dispute_fee = fee; LogSetDisputeFee(fee); } /// @notice Set a custom fee for this particular question /// @param question_id The question in question /// @param fee The fee amount function setCustomDisputeFee(bytes32 question_id, uint256 fee) onlyOwner public { custom_dispute_fees[question_id] = fee; LogSetCustomDisputeFee(question_id, fee); } /// @notice Return the dispute fee for the specified question. 0 indicates that we won't arbitrate it. /// @param question_id The question in question /// @dev Uses a general default, but can be over-ridden on a question-by-question basis. function getDisputeFee(bytes32 question_id) public constant returns (uint256) { return (custom_dispute_fees[question_id] > 0) ? custom_dispute_fees[question_id] : dispute_fee; } /// @notice Set a fee for asking a question with us as the arbitrator /// @param realitycheck The RealityCheck contract address /// @param fee The fee amount /// @dev Default is no fee. Unlike the dispute fee, 0 is an acceptable setting. /// You could set an impossibly high fee if you want to prevent us being used as arbitrator unless we submit the question. /// (Submitting the question ourselves is not implemented here.) /// This fee can be used as a revenue source, an anti-spam measure, or both. function setQuestionFee(address realitycheck, uint256 fee) onlyOwner public { RealityCheckAPI(realitycheck).setQuestionFee(fee); LogSetQuestionFee(fee); } /// @notice Submit the arbitrator's answer to a question. /// @param realitycheck The RealityCheck contract address /// @param question_id The question in question /// @param answer The answer /// @param answerer The answerer. If arbitration changed the answer, it should be the payer. If not, the old answerer. function submitAnswerByArbitrator(address realitycheck, bytes32 question_id, bytes32 answer, address answerer) onlyOwner public { delete arbitration_bounties[question_id]; RealityCheckAPI(realitycheck).submitAnswerByArbitrator(question_id, answer, answerer); } /// @notice Request arbitration, freezing the question until we send submitAnswerByArbitrator /// @dev The bounty can be paid only in part, in which case the last person to pay will be considered the payer /// Will trigger an error if the notification fails, eg because the question has already been finalized /// @param realitycheck The RealityCheck contract address /// @param question_id The question in question function requestArbitration(address realitycheck, bytes32 question_id) external payable returns (bool) { uint256 arbitration_fee = getDisputeFee(question_id); require(arbitration_fee > 0); arbitration_bounties[question_id] += msg.value; uint256 paid = arbitration_bounties[question_id]; if (paid >= arbitration_fee) { RealityCheckAPI(realitycheck).notifyOfArbitrationRequest(question_id, msg.sender); LogRequestArbitration(question_id, msg.value, msg.sender, 0); return true; } else { require(!RealityCheckAPI(realitycheck).isFinalized(question_id)); LogRequestArbitration(question_id, msg.value, msg.sender, arbitration_fee - paid); return false; } } /// @notice Withdraw any accumulated fees to the specified address /// @param addr The address to which the balance should be sent function withdraw(address addr) onlyOwner public { addr.transfer(this.balance); } function() public payable { } /// @notice Withdraw any accumulated question fees from the specified address into this contract /// @param realitycheck The address of the Reality Check contract containing the fees /// @dev Funds can then be liberated from this contract with our withdraw() function function callWithdraw(address realitycheck) onlyOwner public { RealityCheckAPI(realitycheck).withdraw(); } }
Submit the arbitrator's answer to a question. realitycheck The RealityCheck contract address question_id The question in question answer The answer answerer The answerer. If arbitration changed the answer, it should be the payer. If not, the old answerer.
function submitAnswerByArbitrator(address realitycheck, bytes32 question_id, bytes32 answer, address answerer) onlyOwner public { delete arbitration_bounties[question_id]; RealityCheckAPI(realitycheck).submitAnswerByArbitrator(question_id, answer, answerer); }
12,969,742
// SPDX-License-Identifier: UNLICENSED // (c) Copyright 2021 YieldMagic LLC. All rights reserved. // // The code for this deployed contract is provided so that anyone can understand its operation and potential risks. // Anyone may interact with this contract, but the code, design, and documentation are the property of YieldMagic LLC. // The contract may not be derived, modified, or redeployed by anyone without a license granted by YieldMagic LLC. pragma solidity ^0.8.0; import "../MasterChefAdapter.sol"; /// An adapter for standard MasterChef staking and liquidity pools contract StandardMasterChefAdapter is MasterChefAdapter { /// @dev See {MasterChefAdapter-constructor} constructor(address SET_STRATEGY) MasterChefAdapter(SET_STRATEGY) {} /// @dev See {MasterChefAdapter-_masterChefBalance} function _masterChefBalance(PoolInfo calldata pool) virtual override internal view returns (uint256) { (uint256 poolTokens, ) = IStandardMasterChef(pool.masterChef).userInfo(pool.masterChefPoolId, address(this)); return poolTokens; } /// @dev See {MasterChefAdapter-_masterChefDeposit} function _masterChefDeposit(PoolInfo calldata pool, uint256 poolTokens) virtual override internal { IStandardMasterChef(pool.masterChef).deposit(pool.masterChefPoolId, poolTokens); } /// @dev See {MasterChefAdapter-_masterChefWithdraw} function _masterChefWithdraw(PoolInfo calldata pool, uint256 poolTokens) virtual override internal { IStandardMasterChef(pool.masterChef).withdraw(pool.masterChefPoolId, poolTokens); } /// @dev See {MasterChefAdapter-_masterChefClaim} function _masterChefClaim(PoolInfo calldata pool) virtual override internal { _masterChefDeposit(pool, 0); } /// @dev See {MasterChefAdapter-_masterChefEmergencyWithdraw} function _masterChefEmergencyWithdraw(PoolInfo calldata pool) virtual override internal { IStandardMasterChef(pool.masterChef).emergencyWithdraw(pool.masterChefPoolId); } } interface IStandardMasterChef { function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; }
See {MasterChefAdapter-_masterChefDeposit}
function _masterChefDeposit(PoolInfo calldata pool, uint256 poolTokens) virtual override internal { IStandardMasterChef(pool.masterChef).deposit(pool.masterChefPoolId, poolTokens); }
12,567,879
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/IStrategy.sol"; import "../interfaces/IVault.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; abstract contract ReaperBaseStrategyv1_1 is IStrategy, UUPSUpgradeable, AccessControlEnumerableUpgradeable, PausableUpgradeable { uint256 public constant PERCENT_DIVISOR = 10_000; uint256 public constant ONE_YEAR = 365 days; uint256 public constant UPGRADE_TIMELOCK = 480 hours; // minimum 48 hours for RF struct Harvest { uint256 timestamp; uint256 vaultSharePrice; } Harvest[] public harvestLog; uint256 public harvestLogCadence; uint256 public lastHarvestTimestamp; uint256 public upgradeProposalTime; /** * Reaper Roles */ bytes32 public constant STRATEGIST = keccak256("STRATEGIST"); bytes32 public constant STRATEGIST_MULTISIG = keccak256("STRATEGIST_MULTISIG"); /** * @dev Reaper contracts: * {treasury} - Address of the Reaper treasury * {vault} - Address of the vault that controls the strategy's funds. * {strategistRemitter} - Address where strategist fee is remitted to. */ address public treasury; address public vault; address public strategistRemitter; /** * Fee related constants: * {MAX_FEE} - Maximum fee allowed by the strategy. Hard-capped at 10%. * {STRATEGIST_MAX_FEE} - Maximum strategist fee allowed by the strategy (as % of treasury fee). * Hard-capped at 50% * {MAX_SECURITY_FEE} - Maximum security fee charged on withdrawal to prevent * flash deposit/harvest attacks. */ uint256 public constant MAX_FEE = 1000; uint256 public constant STRATEGIST_MAX_FEE = 5000; uint256 public constant MAX_SECURITY_FEE = 10; /** * @dev Distribution of fees earned, expressed as % of the profit from each harvest. * {totalFee} - divided by 10,000 to determine the % fee. Set to 4.5% by default and * lowered as necessary to provide users with the most competitive APY. * * {callFee} - Percent of the totalFee reserved for the harvester (1000 = 10% of total fee: 0.45% by default) * {treasuryFee} - Percent of the totalFee taken by maintainers of the software (9000 = 90% of total fee: 4.05% by default) * {strategistFee} - Percent of the treasuryFee taken by strategist (2500 = 25% of treasury fee: 1.0125% by default) * * {securityFee} - Fee taxed when a user withdraws funds. Taken to prevent flash deposit/harvest attacks. * These funds are redistributed to stakers in the pool. */ uint256 public totalFee; uint256 public callFee; uint256 public treasuryFee; uint256 public strategistFee; uint256 public securityFee; /** * {TotalFeeUpdated} Event that is fired each time the total fee is updated. * {FeesUpdated} Event that is fired each time callFee+treasuryFee+strategistFee are updated. * {StratHarvest} Event that is fired each time the strategy gets harvested. * {StrategistRemitterUpdated} Event that is fired each time the strategistRemitter address is updated. */ event TotalFeeUpdated(uint256 newFee); event FeesUpdated( uint256 newCallFee, uint256 newTreasuryFee, uint256 newStrategistFee ); event StratHarvest(address indexed harvester); event StrategistRemitterUpdated(address newStrategistRemitter); /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function __ReaperBaseStrategy_init( address _vault, address[] memory _feeRemitters, address[] memory _strategists ) internal onlyInitializing { __UUPSUpgradeable_init(); __AccessControlEnumerable_init(); __Pausable_init_unchained(); harvestLogCadence = 1 minutes; totalFee = 450; callFee = 1000; treasuryFee = 9000; strategistFee = 2500; securityFee = 10; _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); clearUpgradeCooldown(); vault = _vault; treasury = _feeRemitters[0]; strategistRemitter = _feeRemitters[1]; for (uint256 i = 0; i < _strategists.length; i++) { _grantRole(STRATEGIST, _strategists[i]); } harvestLog.push( Harvest({ timestamp: block.timestamp, vaultSharePrice: IVault(_vault).getPricePerFullShare() }) ); } /** * @dev Function that puts the funds to work. * It gets called whenever someone deposits in the strategy's vault contract. * Deposits go through only when the strategy is not paused. */ function deposit() public override whenNotPaused { _deposit(); } /** * @dev Withdraws funds and sends them back to the vault. Can only * be called by the vault. _amount must be valid and security fee * is deducted up-front. */ function withdraw(uint256 _amount) external override { require(msg.sender == vault, "!vault"); require(_amount != 0, "invalid amount"); require(_amount <= balanceOf(), "invalid amount"); uint256 withdrawFee = (_amount * securityFee) / PERCENT_DIVISOR; _amount -= withdrawFee; _withdraw(_amount); } /** * @dev harvest() function that takes care of logging. Subcontracts should * override _harvestCore() and implement their specific logic in it. */ function harvest() external override whenNotPaused { _harvestCore(); if ( block.timestamp >= harvestLog[harvestLog.length - 1].timestamp + harvestLogCadence ) { harvestLog.push( Harvest({ timestamp: block.timestamp, vaultSharePrice: IVault(vault).getPricePerFullShare() }) ); } lastHarvestTimestamp = block.timestamp; emit StratHarvest(msg.sender); } function harvestLogLength() external view returns (uint256) { return harvestLog.length; } /** * @dev Traverses the harvest log backwards _n items, * and returns the average APR calculated across all the included * log entries. APR is multiplied by PERCENT_DIVISOR to retain precision. */ function averageAPRAcrossLastNHarvests(int256 _n) external view returns (int256) { require(harvestLog.length >= 2, "need at least 2 log entries"); int256 runningAPRSum; int256 numLogsProcessed; for ( uint256 i = harvestLog.length - 1; i > 0 && numLogsProcessed < _n; i-- ) { runningAPRSum += calculateAPRUsingLogs(i - 1, i); numLogsProcessed++; } return runningAPRSum / numLogsProcessed; } /** * @dev Only strategist or owner can edit the log cadence. */ function updateHarvestLogCadence(uint256 _newCadenceInSeconds) external { _onlyStrategistOrOwner(); harvestLogCadence = _newCadenceInSeconds; } /** * @dev Function to calculate the total {want} held by the strat. * It takes into account both the funds in hand, plus the funds in external contracts. */ function balanceOf() public view virtual override returns (uint256); /** * @dev Function to retire the strategy. Claims all rewards and withdraws * all principal from external contracts, and sends everything back to * the vault. Can only be called by strategist or owner. * * Note: this is not an emergency withdraw function. For that, see panic(). */ function retireStrat() external override { _onlyStrategistOrOwner(); _retireStrat(); } /** * @dev Pauses deposits. Withdraws all funds leaving rewards behind */ function panic() external override { _onlyStrategistOrOwner(); _reclaimWant(); pause(); } /** * @dev Pauses the strat. Deposits become disabled but users can still * withdraw. Removes allowances of external contracts. */ function pause() public override { _onlyStrategistOrOwner(); _pause(); _removeAllowances(); } /** * @dev Unpauses the strat. Opens up deposits again and invokes deposit(). * Reinstates allowances for external contracts. */ function unpause() external override { _onlyStrategistOrOwner(); _unpause(); _giveAllowances(); deposit(); } /** * @dev updates the total fee, capped at 5%; only owner. */ function updateTotalFee(uint256 _totalFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_totalFee <= MAX_FEE, "Fee Too High"); totalFee = _totalFee; emit TotalFeeUpdated(totalFee); } /** * @dev updates the call fee, treasury fee, and strategist fee * call Fee + treasury Fee must add up to PERCENT_DIVISOR * * strategist fee is expressed as % of the treasury fee and * must be no more than STRATEGIST_MAX_FEE * * only owner */ function updateFees( uint256 _callFee, uint256 _treasuryFee, uint256 _strategistFee ) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool) { require( _callFee + _treasuryFee == PERCENT_DIVISOR, "sum != PERCENT_DIVISOR" ); require( _strategistFee <= STRATEGIST_MAX_FEE, "strategist fee > STRATEGIST_MAX_FEE" ); callFee = _callFee; treasuryFee = _treasuryFee; strategistFee = _strategistFee; emit FeesUpdated(callFee, treasuryFee, strategistFee); return true; } function updateSecurityFee(uint256 _securityFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_securityFee <= MAX_SECURITY_FEE, "fee to high!"); securityFee = _securityFee; } /** * @dev only owner can update treasury address. */ function updateTreasury(address newTreasury) external onlyRole(DEFAULT_ADMIN_ROLE) returns (bool) { treasury = newTreasury; return true; } /** * @dev Updates the current strategistRemitter. * If there is only one strategist this function may be called by * that strategist. However if there are multiple strategists * this function may only be called by the STRATEGIST_MULTISIG role. */ function updateStrategistRemitter(address _newStrategistRemitter) external { if (getRoleMemberCount(STRATEGIST) == 1) { _checkRole(STRATEGIST, msg.sender); } else { _checkRole(STRATEGIST_MULTISIG, msg.sender); } require(_newStrategistRemitter != address(0), "!0"); strategistRemitter = _newStrategistRemitter; emit StrategistRemitterUpdated(_newStrategistRemitter); } /** * @dev Only allow access to strategist or owner */ function _onlyStrategistOrOwner() internal view { require( hasRole(STRATEGIST, msg.sender) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized" ); } /** * @dev Project an APR using the vault share price change between harvests at the provided indices. */ function calculateAPRUsingLogs(uint256 _startIndex, uint256 _endIndex) public view returns (int256) { Harvest storage start = harvestLog[_startIndex]; Harvest storage end = harvestLog[_endIndex]; bool increasing = true; if (end.vaultSharePrice < start.vaultSharePrice) { increasing = false; } uint256 unsignedSharePriceChange; if (increasing) { unsignedSharePriceChange = end.vaultSharePrice - start.vaultSharePrice; } else { unsignedSharePriceChange = start.vaultSharePrice - end.vaultSharePrice; } uint256 unsignedPercentageChange = (unsignedSharePriceChange * 1e18) / start.vaultSharePrice; uint256 timeDifference = end.timestamp - start.timestamp; uint256 yearlyUnsignedPercentageChange = (unsignedPercentageChange * ONE_YEAR) / timeDifference; yearlyUnsignedPercentageChange /= 1e14; // restore basis points precision if (increasing) { return int256(yearlyUnsignedPercentageChange); } return -int256(yearlyUnsignedPercentageChange); } /** * @dev DEFAULT_ADMIN_ROLE must call this function prior to upgrading the implementation * and wait UPGRADE_TIMELOCK seconds before executing the upgrade. */ function initiateUpgradeCooldown() external onlyRole(DEFAULT_ADMIN_ROLE) { upgradeProposalTime = block.timestamp; } /** * @dev This function is called: * - in initialize() * - as part of a successful upgrade * - manually by DEFAULT_ADMIN_ROLE to clear the upgrade cooldown. */ function clearUpgradeCooldown() public onlyRole(DEFAULT_ADMIN_ROLE) { upgradeProposalTime = block.timestamp + (ONE_YEAR * 100); } /** * @dev This function must be overriden simply for access control purposes. * Only DEFAULT_ADMIN_ROLE can upgrade the implementation once the timelock * has passed. */ function _authorizeUpgrade(address) internal override onlyRole(DEFAULT_ADMIN_ROLE) { require( upgradeProposalTime + UPGRADE_TIMELOCK < block.timestamp, "cooldown not initiated or still active" ); clearUpgradeCooldown(); } /** * @dev subclasses should add their custom deposit logic in this function. */ function _deposit() internal virtual; /** * @dev subclasses should add their custom withdraw logic in this function. * Note that security fee has already been deducted, so it shouldn't be deducted * again within this function. */ function _withdraw(uint256 _amount) internal virtual; /** * @dev subclasses should add their custom harvesting logic in this function * including charging any fees. */ function _harvestCore() internal virtual; /** * @dev subclasses should add their custom logic to retire the strategy in this function. * Note that we expect all funds (including any pending rewards) to be sent back to * the vault in this function. */ function _retireStrat() internal virtual; /** * @dev subclasses should add their custom logic to withdraw the principal from * any external contracts in this function. Note that we don't care about rewards, * we just want to reclaim our principal as much as possible, and as quickly as possible. * So keep this function lean. Principal should be left in the strategy and not sent to * the vault. */ function _reclaimWant() internal virtual; /** * @dev subclasses should add their custom logic to give allowances to external contracts * so the strategy can successfully interface with them. */ function _giveAllowances() internal virtual; /** * @dev subclasses should add their custom logic to remove all allowances for any external * contracts. */ function _removeAllowances() internal virtual; }
This function must be overriden simply for access control purposes. Only DEFAULT_ADMIN_ROLE can upgrade the implementation once the timelock has passed./
function _authorizeUpgrade(address) internal override onlyRole(DEFAULT_ADMIN_ROLE) { require( upgradeProposalTime + UPGRADE_TIMELOCK < block.timestamp, "cooldown not initiated or still active" ); clearUpgradeCooldown(); }
1,799,826
// SPDX-License-Identifier: MIT pragma solidity 0.7.0; import "./IERC20.sol"; import "./IMintableToken.sol"; import "./IDividends.sol"; import "./SafeMath.sol"; contract Token is IERC20, IMintableToken, IDividends { using SafeMath for uint256; uint256 public totalSupply; uint256 public decimals = 18; string public name = "Test token"; string public symbol = "TEST"; mapping (address => uint256) public balanceOf; // Events event Transfer(address from, address to, uint256 value); event Approval(address owner, address spender, uint256 value); event Minted(uint amount); event Burned(uint amount); // Variables uint public scaledDividendPerToken; uint public scaling = 10**8; // Mappings mapping (address => mapping (address => uint256)) internal allowed; mapping (address => uint) scaledOutstandingDividend; mapping (address => uint) scaledDividendCreditedTo; /** * @dev Updates individual address dividends */ function update(address _address) private { uint owed = scaledDividendPerToken - scaledDividendCreditedTo[_address]; scaledOutstandingDividend[_address] += balanceOf[_address] * owed; scaledDividendCreditedTo[_address] = scaledDividendPerToken; } // IERC20 /** * @dev Returns the amount which 'spender' is still allowed to withdraw from 'owner'. */ function allowance(address owner, address spender) external view override returns (uint256) { return allowed[owner][spender]; } /** * @dev Transfers 'value' amount of tokens to address 'to'. * * Throws if the message caller’s account balance does not have enough tokens to spend. * * Emits {Transfer} event. */ function transfer(address to, uint256 value) external override returns (bool) { require(msg.sender != to); require(to != address(0)); require(value <= balanceOf[msg.sender]); update(msg.sender); update(to); balanceOf[msg.sender] -= value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return true; } /** * @dev Allows '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'. * * Emits {Approval} event. */ function approve(address spender, uint256 value) external override returns (bool) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfers 'value' amount of tokens from address 'from' to address 'to'. * * Emits {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external override returns (bool) { require(to != from); require(to != address(0)); require(value <= balanceOf[from]); require(value <= allowed[from][msg.sender]); update(msg.sender); update(to); balanceOf[from] -= value; balanceOf[to] += value; allowed[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } // IMintableToken /** * @dev Deposit ETH and mint equal no. of tokens to the caller's balance. * * Throws error if no ETH is supplied. * * Emits {Minted} event. */ function mint() external payable override { require(msg.value > 0, "No ETH supplied."); update(msg.sender); balanceOf[msg.sender] += msg.value; totalSupply += msg.value; emit Minted(msg.value); } /** * @dev Burn caller's token balance and send the equivalent amount of ETH to given destination address. * * Throws error if no token balance is zero. */ function burn(address payable dest) external override { uint burnAmount = balanceOf[msg.sender]; require(burnAmount > 0, "No tokens to burn."); update(msg.sender); balanceOf[msg.sender] -= burnAmount; totalSupply -= burnAmount; dest.transfer(burnAmount); emit Burned(burnAmount); } // IDividends uint public scaledRemainder = 0; function recordDividend() external payable override { // scale the deposit and add the previous remainder uint256 available = (msg.value * scaling) + scaledRemainder; scaledDividendPerToken += available / totalSupply; // compute the new remainder scaledRemainder = available % totalSupply; } function getWithdrawableDividend(address payee) external view override returns (uint256) { // update(payee); would throw error as non-payable view function return (scaledOutstandingDividend[msg.sender] / scaling); // technically not up to date } function withdrawDividend(address payable dest) external override { update(msg.sender); uint256 amount = scaledOutstandingDividend[msg.sender] / scaling; scaledOutstandingDividend[msg.sender] %= scaling; // retain the remainder dest.transfer(amount); } }
scale the deposit and add the previous remainder compute the new remainder
function recordDividend() external payable override { uint256 available = (msg.value * scaling) + scaledRemainder; scaledDividendPerToken += available / totalSupply; scaledRemainder = available % totalSupply; }
12,545,298
/** *Submitted for verification at Etherscan.io on 2022-03-15 */ // SPDX-License-Identifier: GPL-3.0-or-later // Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library 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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of 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)); } } // File interfaces/IStrategy.sol pragma solidity 0.8.9; interface IStrategy { function name() external view returns (string memory); function deposit() external payable returns (bool); function balance() external view returns (uint256); function withdraw(uint256 amount) external returns (bool); function withdrawAll() external returns (uint256); function harvestable() external view returns (uint256); function harvest() external returns (uint256); function strategist() external view returns (address); function shutdown() external returns (bool); function hasPendingFunds() external view returns (bool); } // File interfaces/IPreparable.sol pragma solidity 0.8.9; interface IPreparable { event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay); event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay); event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue); event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue); event ConfigReset(bytes32 indexed key); } // File interfaces/IVault.sol pragma solidity 0.8.9; /** * @title Interface for a Vault */ interface IVault is IPreparable { event StrategyActivated(address indexed strategy); event StrategyDeactivated(address indexed strategy); /** * @dev 'netProfit' is the profit after all fees have been deducted */ event Harvest(uint256 indexed netProfit, uint256 indexed loss); function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external; function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256); function deposit() external payable; function withdraw(uint256 amount) external returns (bool); function initializeStrategy(address strategy_) external returns (bool); function withdrawAll() external; function withdrawFromReserve(uint256 amount) external; function getStrategy() external view returns (IStrategy); function getStrategiesWaitingForRemoval() external view returns (address[] memory); function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256); function getTotalUnderlying() external view returns (uint256); function getUnderlying() external view returns (address); } // File interfaces/IVaultReserve.sol pragma solidity 0.8.9; interface IVaultReserve { event Deposit(address indexed vault, address indexed token, uint256 amount); event Withdraw(address indexed vault, address indexed token, uint256 amount); event VaultListed(address indexed vault); function deposit(address token, uint256 amount) external payable returns (bool); function withdraw(address token, uint256 amount) external returns (bool); function getBalance(address vault, address token) external view returns (uint256); function canWithdraw(address vault) external view returns (bool); } // File interfaces/pool/ILiquidityPool.sol pragma solidity 0.8.9; interface ILiquidityPool is IPreparable { event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens); event DepositFor( address indexed minter, address indexed mintee, uint256 depositAmount, uint256 mintedLpTokens ); event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens); event LpTokenSet(address indexed lpToken); event StakerVaultSet(address indexed stakerVault); function redeem(uint256 redeemTokens) external returns (uint256); function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256); function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256); function deposit(uint256 mintAmount) external payable returns (uint256); function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256); function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable returns (uint256); function depositFor(address account, uint256 depositAmount) external payable returns (uint256); function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) external payable returns (uint256); function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external returns (uint256); function handleLpTokenTransfer( address from, address to, uint256 amount ) external; function executeNewVault() external returns (address); function executeNewMaxWithdrawalFee() external returns (uint256); function executeNewRequiredReserves() external returns (uint256); function executeNewReserveDeviation() external returns (uint256); function setLpToken(address _lpToken) external returns (bool); function setStaker() external returns (bool); function isCapped() external returns (bool); function uncap() external returns (bool); function updateDepositCap(uint256 _depositCap) external returns (bool); function getUnderlying() external view returns (address); function getLpToken() external view returns (address); function getWithdrawalFee(address account, uint256 amount) external view returns (uint256); function getVault() external view returns (IVault); function exchangeRate() external view returns (uint256); } // File interfaces/IGasBank.sol pragma solidity 0.8.9; interface IGasBank { event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, address indexed receiver, uint256 value); function depositFor(address account) external payable; function withdrawUnused(address account) external; function withdrawFrom(address account, uint256 amount) external; function withdrawFrom( address account, address payable to, uint256 amount ) external; function balanceOf(address account) external view returns (uint256); } // File interfaces/oracles/IOracleProvider.sol pragma solidity 0.8.9; interface IOracleProvider { /// @notice Quotes the USD price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the USD price of the asset function getPriceUSD(address baseAsset) external view returns (uint256); /// @notice Quotes the ETH price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the ETH price of the asset function getPriceETH(address baseAsset) external view returns (uint256); } // File libraries/AddressProviderMeta.sol pragma solidity 0.8.9; library AddressProviderMeta { struct Meta { bool freezable; bool frozen; } function fromUInt(uint256 value) internal pure returns (Meta memory) { Meta memory meta; meta.freezable = (value & 1) == 1; meta.frozen = ((value >> 1) & 1) == 1; return meta; } function toUInt(Meta memory meta) internal pure returns (uint256) { uint256 value; value |= meta.freezable ? 1 : 0; value |= meta.frozen ? 1 << 1 : 0; return value; } } // File interfaces/IAddressProvider.sol pragma solidity 0.8.9; // solhint-disable ordering interface IAddressProvider is IPreparable { event KnownAddressKeyAdded(bytes32 indexed key); event StakerVaultListed(address indexed stakerVault); event StakerVaultDelisted(address indexed stakerVault); event ActionListed(address indexed action); event PoolListed(address indexed pool); event PoolDelisted(address indexed pool); event VaultUpdated(address indexed previousVault, address indexed newVault); /** Key functions */ function getKnownAddressKeys() external view returns (bytes32[] memory); function freezeAddress(bytes32 key) external; /** Pool functions */ function allPools() external view returns (address[] memory); function addPool(address pool) external; function poolsCount() external view returns (uint256); function getPoolAtIndex(uint256 index) external view returns (address); function isPool(address pool) external view returns (bool); function removePool(address pool) external returns (bool); function getPoolForToken(address token) external view returns (ILiquidityPool); function safeGetPoolForToken(address token) external view returns (address); /** Vault functions */ function updateVault(address previousVault, address newVault) external; function allVaults() external view returns (address[] memory); function vaultsCount() external view returns (uint256); function getVaultAtIndex(uint256 index) external view returns (address); function isVault(address vault) external view returns (bool); /** Action functions */ function allActions() external view returns (address[] memory); function addAction(address action) external returns (bool); function isAction(address action) external view returns (bool); /** Address functions */ function initializeAddress( bytes32 key, address initialAddress, bool frezable ) external; function initializeAndFreezeAddress(bytes32 key, address initialAddress) external; function getAddress(bytes32 key) external view returns (address); function getAddress(bytes32 key, bool checkExists) external view returns (address); function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory); function prepareAddress(bytes32 key, address newAddress) external returns (bool); function executeAddress(bytes32 key) external returns (address); function resetAddress(bytes32 key) external returns (bool); /** Staker vault functions */ function allStakerVaults() external view returns (address[] memory); function tryGetStakerVault(address token) external view returns (bool, address); function getStakerVault(address token) external view returns (address); function addStakerVault(address stakerVault) external returns (bool); function isStakerVault(address stakerVault, address token) external view returns (bool); function isStakerVaultRegistered(address stakerVault) external view returns (bool); function isWhiteListedFeeHandler(address feeHandler) external view returns (bool); } // File interfaces/tokenomics/IInflationManager.sol pragma solidity 0.8.9; interface IInflationManager { event KeeperGaugeListed(address indexed pool, address indexed keeperGauge); event AmmGaugeListed(address indexed token, address indexed ammGauge); event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge); event AmmGaugeDelisted(address indexed token, address indexed ammGauge); /** Pool functions */ function setKeeperGauge(address pool, address _keeperGauge) external returns (bool); function setAmmGauge(address token, address _ammGauge) external returns (bool); function getAllAmmGauges() external view returns (address[] memory); function getLpRateForStakerVault(address stakerVault) external view returns (uint256); function getKeeperRateForPool(address pool) external view returns (uint256); function getAmmRateForToken(address token) external view returns (uint256); function getKeeperWeightForPool(address pool) external view returns (uint256); function getAmmWeightForToken(address pool) external view returns (uint256); function getLpPoolWeight(address pool) external view returns (uint256); function getKeeperGaugeForPool(address pool) external view returns (address); function getAmmGaugeForToken(address token) external view returns (address); function isInflationWeightManager(address account) external view returns (bool); function removeStakerVaultFromInflation(address stakerVault, address lpToken) external; function addGaugeForVault(address lpToken) external returns (bool); function whitelistGauge(address gauge) external; function checkpointAllGauges() external returns (bool); function mintRewards(address beneficiary, uint256 amount) external; function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool) external returns (bool); /** Weight setter functions **/ function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool); function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool); function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool); function executeLpPoolWeight(address lpToken) external returns (uint256); function executeAmmTokenWeight(address token) external returns (uint256); function executeKeeperPoolWeight(address pool) external returns (uint256); function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights) external returns (bool); function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights) external returns (bool); function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights) external returns (bool); function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool); function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool); function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool); } // File interfaces/IController.sol pragma solidity 0.8.9; // solhint-disable ordering interface IController is IPreparable { function addressProvider() external view returns (IAddressProvider); function inflationManager() external view returns (IInflationManager); function addStakerVault(address stakerVault) external returns (bool); function removePool(address pool) external returns (bool); /** Keeper functions */ function prepareKeeperRequiredStakedBKD(uint256 amount) external; function executeKeeperRequiredStakedBKD() external; function getKeeperRequiredStakedBKD() external view returns (uint256); function canKeeperExecuteAction(address keeper) external view returns (bool); /** Miscellaneous functions */ function getTotalEthRequiredForGas(address payer) external view returns (uint256); } // File libraries/ScaledMath.sol pragma solidity 0.8.9; /* * @dev To use functions of this contract, at least one of the numbers must * be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE` * if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale * of the number not scaled by `DECIMAL_SCALE` */ library ScaledMath { // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant DECIMAL_SCALE = 1e18; // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant ONE = 1e18; /** * @notice Performs a multiplication between two scaled numbers */ function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) { return (a * b) / DECIMAL_SCALE; } /** * @notice Performs a division between two scaled numbers */ function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE) / b; } /** * @notice Performs a division between two numbers, rounding up the result */ function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE + b - 1) / b; } /** * @notice Performs a division between two numbers, ignoring any scaling and rounding up the result */ function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a + b - 1) / b; } } // File libraries/Errors.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Error { string internal constant ADDRESS_WHITELISTED = "address already whitelisted"; string internal constant ADMIN_ALREADY_SET = "admin has already been set once"; string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted"; string internal constant ADDRESS_NOT_FOUND = "address not found"; string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once"; string internal constant CONTRACT_PAUSED = "contract is paused"; string internal constant INVALID_AMOUNT = "invalid amount"; string internal constant INVALID_INDEX = "invalid index"; string internal constant INVALID_VALUE = "invalid msg.value"; string internal constant INVALID_SENDER = "invalid msg.sender"; string internal constant INVALID_TOKEN = "token address does not match pool's LP token address"; string internal constant INVALID_DECIMALS = "incorrect number of decimals"; string internal constant INVALID_ARGUMENT = "invalid argument"; string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted"; string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_POOL_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_LP_TOKEN_IMPLEMENTATION = "invalid LP Token implementation for given coin"; string internal constant INVALID_VAULT_IMPLEMENTATION = "invalid vault implementation for given coin"; string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION = "invalid stakerVault implementation for given coin"; string internal constant INSUFFICIENT_BALANCE = "insufficient balance"; string internal constant ADDRESS_ALREADY_SET = "Address is already set"; string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance"; string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received"; string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist"; string internal constant ADDRESS_FROZEN = "address is frozen"; string internal constant ROLE_EXISTS = "role already exists"; string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role"; string internal constant UNAUTHORIZED_ACCESS = "unauthorized access"; string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed"; string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed"; string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed"; string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed"; string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10"; string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold"; string internal constant NO_POSITION_EXISTS = "no position exists"; string internal constant POSITION_ALREADY_EXISTS = "position already exists"; string internal constant PROTOCOL_NOT_FOUND = "protocol not found"; string internal constant TOP_UP_FAILED = "top up failed"; string internal constant SWAP_PATH_NOT_FOUND = "swap path not found"; string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported"; string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN = "not enough funds were withdrawn from the pool"; string internal constant FAILED_TRANSFER = "transfer failed"; string internal constant FAILED_MINT = "mint failed"; string internal constant FAILED_REPAY_BORROW = "repay borrow failed"; string internal constant FAILED_METHOD_CALL = "method call failed"; string internal constant NOTHING_TO_CLAIM = "there is no claimable balance"; string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance"; string internal constant INVALID_MINTER = "the minter address of the LP token and the pool address do not match"; string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token"; string internal constant DEADLINE_NOT_ZERO = "deadline must be 0"; string internal constant DEADLINE_NOT_SET = "deadline is 0"; string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet"; string internal constant DELAY_TOO_SHORT = "delay be at least 3 days"; string internal constant INSUFFICIENT_UPDATE_BALANCE = "insufficient funds for updating the position"; string internal constant SAME_AS_CURRENT = "value must be different to existing value"; string internal constant NOT_CAPPED = "the pool is not currently capped"; string internal constant ALREADY_CAPPED = "the pool is already capped"; string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap"; string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas"; string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw"; string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas"; string internal constant DEPOSIT_FAILED = "deposit failed"; string internal constant GAS_TOO_HIGH = "too much ETH used for gas"; string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas"; string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add"; string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed"; string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet"; string internal constant UNDERLYING_NOT_WITHDRAWABLE = "pool does not support additional underlying coins to be withdrawn"; string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down"; string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist"; string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported"; string internal constant NO_DEX_SET = "no dex has been set for token"; string internal constant INVALID_TOKEN_PAIR = "invalid token pair"; string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action"; string internal constant ADDRESS_NOT_ACTION = "address is not registered action"; string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance"; string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve"; string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block"; string internal constant GAUGE_EXISTS = "Gauge already exists"; string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist"; string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex"; string internal constant PREPARED_WITHDRAWAL = "Cannot relock funds when withdrawal is being prepared"; string internal constant ASSET_NOT_SUPPORTED = "Asset not supported"; string internal constant STALE_PRICE = "Price is stale"; string internal constant NEGATIVE_PRICE = "Price is negative"; string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked"; string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded"; } // File @openzeppelin/contracts/utils/structs/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File libraries/EnumerableMapping.sol pragma solidity 0.8.9; library EnumerableMapping { using EnumerableSet for EnumerableSet.Bytes32Set; // Code take from contracts/utils/structs/EnumerableMap.sol // because the helper functions are private // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } // AddressToAddressMap struct AddressToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( AddressToAddressMap storage map, address key, address value ) internal returns (bool) { return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(AddressToAddressMap storage map, address key) internal returns (bool) { return _remove(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(AddressToAddressMap storage map, address key) internal view returns (bool) { return _contains(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns the number of elements in the map. O(1). */ function length(AddressToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressToAddressMap storage map, uint256 index) internal view returns (address, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (address(uint160(uint256(key))), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(AddressToAddressMap storage map, address key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key)))); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(AddressToAddressMap storage map, address key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(uint256(uint160(key))))))); } // AddressToUintMap struct AddressToUintMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( AddressToUintMap storage map, address key, uint256 value ) internal returns (bool) { return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(AddressToUintMap storage map, address key) internal returns (bool) { return _remove(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(AddressToUintMap storage map, address key) internal view returns (bool) { return _contains(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns the number of elements in the map. O(1). */ function length(AddressToUintMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (address(uint160(uint256(key))), uint256(value)); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key)))); return (success, uint256(value)); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(AddressToUintMap storage map, address key) internal view returns (uint256) { return uint256(_get(map._inner, bytes32(uint256(uint160(key))))); } // Bytes32ToUIntMap struct Bytes32ToUIntMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( Bytes32ToUIntMap storage map, bytes32 key, uint256 value ) internal returns (bool) { return _set(map._inner, key, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(Bytes32ToUIntMap storage map, bytes32 key) internal returns (bool) { return _remove(map._inner, key); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (bool) { return _contains(map._inner, key); } /** * @dev Returns the number of elements in the map. O(1). */ function length(Bytes32ToUIntMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32ToUIntMap storage map, uint256 index) internal view returns (bytes32, uint256) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (key, uint256(value)); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (bool, uint256) { (bool success, bytes32 value) = _tryGet(map._inner, key); return (success, uint256(value)); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (uint256) { return uint256(_get(map._inner, key)); } } // File libraries/EnumerableExtensions.sol pragma solidity 0.8.9; library EnumerableExtensions { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.Bytes32Set; using EnumerableMapping for EnumerableMapping.AddressToAddressMap; using EnumerableMapping for EnumerableMapping.AddressToUintMap; using EnumerableMapping for EnumerableMapping.Bytes32ToUIntMap; function toArray(EnumerableSet.AddressSet storage addresses) internal view returns (address[] memory) { uint256 len = addresses.length(); address[] memory result = new address[](len); for (uint256 i = 0; i < len; i++) { result[i] = addresses.at(i); } return result; } function toArray(EnumerableSet.Bytes32Set storage values) internal view returns (bytes32[] memory) { uint256 len = values.length(); bytes32[] memory result = new bytes32[](len); for (uint256 i = 0; i < len; i++) { result[i] = values.at(i); } return result; } function keyAt(EnumerableMapping.AddressToAddressMap storage map, uint256 index) internal view returns (address) { (address key, ) = map.at(index); return key; } function valueAt(EnumerableMapping.AddressToAddressMap storage map, uint256 index) internal view returns (address) { (, address value) = map.at(index); return value; } function keyAt(EnumerableMapping.AddressToUintMap storage map, uint256 index) internal view returns (address) { (address key, ) = map.at(index); return key; } function keyAt(EnumerableMapping.Bytes32ToUIntMap storage map, uint256 index) internal view returns (bytes32) { (bytes32 key, ) = map.at(index); return key; } function valueAt(EnumerableMapping.AddressToUintMap storage map, uint256 index) internal view returns (uint256) { (, uint256 value) = map.at(index); return value; } function keysArray(EnumerableMapping.AddressToAddressMap storage map) internal view returns (address[] memory) { uint256 len = map.length(); address[] memory result = new address[](len); for (uint256 i = 0; i < len; i++) { result[i] = keyAt(map, i); } return result; } function valuesArray(EnumerableMapping.AddressToAddressMap storage map) internal view returns (address[] memory) { uint256 len = map.length(); address[] memory result = new address[](len); for (uint256 i = 0; i < len; i++) { result[i] = valueAt(map, i); } return result; } function keysArray(EnumerableMapping.AddressToUintMap storage map) internal view returns (address[] memory) { uint256 len = map.length(); address[] memory result = new address[](len); for (uint256 i = 0; i < len; i++) { result[i] = keyAt(map, i); } return result; } function keysArray(EnumerableMapping.Bytes32ToUIntMap storage map) internal view returns (bytes32[] memory) { uint256 len = map.length(); bytes32[] memory result = new bytes32[](len); for (uint256 i = 0; i < len; i++) { result[i] = keyAt(map, i); } return result; } } // File interfaces/IRoleManager.sol pragma solidity 0.8.9; interface IRoleManager { event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, address account ) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, bytes32 role3, address account ) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } // File interfaces/tokenomics/IBkdToken.sol pragma solidity 0.8.9; interface IBkdToken is IERC20 { function mint(address account, uint256 amount) external; } // File libraries/AddressProviderKeys.sol pragma solidity 0.8.9; library AddressProviderKeys { bytes32 internal constant _TREASURY_KEY = "treasury"; bytes32 internal constant _GAS_BANK_KEY = "gasBank"; bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve"; bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry"; bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider"; bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory"; bytes32 internal constant _CONTROLLER_KEY = "controller"; bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker"; bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager"; } // File libraries/AddressProviderHelpers.sol pragma solidity 0.8.9; library AddressProviderHelpers { /** * @return The address of the treasury. */ function getTreasury(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._TREASURY_KEY); } /** * @return The gas bank. */ function getGasBank(IAddressProvider provider) internal view returns (IGasBank) { return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY)); } /** * @return The address of the vault reserve. */ function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) { return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY)); } /** * @return The address of the swapperRegistry. */ function getSwapperRegistry(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY); } /** * @return The oracleProvider. */ function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) { return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY)); } /** * @return the address of the BKD locker */ function getBKDLocker(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY); } /** * @return the address of the BKD locker */ function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); } /** * @return the controller */ function getController(IAddressProvider provider) internal view returns (IController) { return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY)); } } // File contracts/vault/VaultStorage.sol pragma solidity 0.8.9; contract VaultStorage { uint256 public currentAllocated; uint256 public waitingForRemovalAllocated; address public pool; uint256 public totalDebt; bool public strategyActive; EnumerableMapping.AddressToUintMap internal _strategiesWaitingForRemoval; } contract VaultStorageV1 is VaultStorage { /** * @dev This is to avoid breaking contracts inheriting from `VaultStorage` * such as `Erc20Vault`, especially if they have storage variables * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps * for more details * * A new field can be added using a new contract such as * * ```solidity * contract VaultStorageV2 is VaultStorage { * uint256 someNewField; * uint256[49] private __gap; * } */ uint256[50] private __gap; } // File contracts/utils/Preparable.sol pragma solidity 0.8.9; /** * @notice Implements the base logic for a two-phase commit * @dev This does not implements any access-control so publicly exposed * callers should make sure to have the proper checks in palce */ contract Preparable is IPreparable { uint256 private constant _MIN_DELAY = 3 days; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingUInts256; mapping(bytes32 => address) public currentAddresses; mapping(bytes32 => uint256) public currentUInts256; /** * @dev Deadlines shares the same namespace regardless of the type * of the pending variable so this needs to be enforced in the caller */ mapping(bytes32 => uint256) public deadlines; function _prepareDeadline(bytes32 key, uint256 delay) internal { require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO); require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT); deadlines[key] = block.timestamp + delay; } /** * @notice Prepares an uint256 that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, uint256 value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingUInts256[key] = value; emit ConfigPreparedNumber(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay */ function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Prepares an address that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, address value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingAddresses[key] = value; emit ConfigPreparedAddress(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay */ function _prepare(bytes32 key, address value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Reset a uint256 key * @return `true` if success. */ function _resetUInt256Config(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingUInts256[key] = 0; emit ConfigReset(key); return true; } /** * @notice Reset an address key * @return `true` if success. */ function _resetAddressConfig(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingAddresses[key] = address(0); emit ConfigReset(key); return true; } /** * @dev Checks the deadline of the key and reset it */ function _executeDeadline(bytes32 key) internal { uint256 deadline = deadlines[key]; require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED); require(deadline != 0, Error.DEADLINE_NOT_SET); deadlines[key] = 0; } /** * @notice Execute uint256 config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeUInt256(bytes32 key) internal returns (uint256) { _executeDeadline(key); uint256 newValue = pendingUInts256[key]; _setConfig(key, newValue); return newValue; } /** * @notice Execute address config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeAddress(bytes32 key) internal returns (address) { _executeDeadline(key); address newValue = pendingAddresses[key]; _setConfig(key, newValue); return newValue; } function _setConfig(bytes32 key, address value) internal returns (address) { address oldValue = currentAddresses[key]; currentAddresses[key] = value; pendingAddresses[key] = address(0); deadlines[key] = 0; emit ConfigUpdatedAddress(key, oldValue, value); return value; } function _setConfig(bytes32 key, uint256 value) internal returns (uint256) { uint256 oldValue = currentUInts256[key]; currentUInts256[key] = value; pendingUInts256[key] = 0; deadlines[key] = 0; emit ConfigUpdatedNumber(key, oldValue, value); return value; } } // File contracts/utils/IPausable.sol pragma solidity 0.8.9; interface IPausable { function pause() external returns (bool); function unpause() external returns (bool); function isPaused() external view returns (bool); function isAuthorizedToPause(address account) external view returns (bool); } // File libraries/Roles.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Roles { bytes32 internal constant GOVERNANCE = "governance"; bytes32 internal constant ADDRESS_PROVIDER = "address_provider"; bytes32 internal constant POOL_FACTORY = "pool_factory"; bytes32 internal constant CONTROLLER = "controller"; bytes32 internal constant GAUGE_ZAP = "gauge_zap"; bytes32 internal constant MAINTENANCE = "maintenance"; bytes32 internal constant INFLATION_MANAGER = "inflation_manager"; bytes32 internal constant POOL = "pool"; bytes32 internal constant VAULT = "vault"; } // File contracts/access/AuthorizationBase.sol pragma solidity 0.8.9; /** * @notice Provides modifiers for authorization */ abstract contract AuthorizationBase { /** * @notice Only allows a sender with `role` to perform the given action */ modifier onlyRole(bytes32 role) { require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with GOVERNANCE role to perform the given action */ modifier onlyGovernance() { require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles2(bytes32 role1, bytes32 role2) { require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles3( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _roleManager().hasAnyRole(role1, role2, role3, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } function roleManager() external view virtual returns (IRoleManager) { return _roleManager(); } function _roleManager() internal view virtual returns (IRoleManager); } // File contracts/access/Authorization.sol pragma solidity 0.8.9; contract Authorization is AuthorizationBase { IRoleManager internal immutable __roleManager; constructor(IRoleManager roleManager) { __roleManager = roleManager; } function _roleManager() internal view override returns (IRoleManager) { return __roleManager; } } // File contracts/vault/Vault.sol pragma solidity 0.8.9; abstract contract Vault is IVault, Authorization, VaultStorageV1, Preparable, Initializable { using ScaledMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableExtensions for EnumerableSet.AddressSet; using EnumerableMapping for EnumerableMapping.AddressToUintMap; using EnumerableExtensions for EnumerableMapping.AddressToUintMap; using AddressProviderHelpers for IAddressProvider; bytes32 internal constant _STRATEGY_KEY = "Strategy"; bytes32 internal constant _PERFORMANCE_FEE_KEY = "PerformanceFee"; bytes32 internal constant _STRATEGIST_FEE_KEY = "StrategistFee"; bytes32 internal constant _DEBT_LIMIT_KEY = "DebtLimit"; bytes32 internal constant _TARGET_ALLOCATION_KEY = "TargetAllocation"; bytes32 internal constant _RESERVE_FEE_KEY = "ReserveFee"; bytes32 internal constant _BOUND_KEY = "Bound"; uint256 internal constant _INITIAL_RESERVE_FEE = 0.01e18; uint256 internal constant _INITIAL_STRATEGIST_FEE = 0.1e18; uint256 internal constant _INITIAL_PERFORMANCE_FEE = 0; uint256 public constant MAX_PERFORMANCE_FEE = 0.5e18; uint256 public constant MAX_DEVIATION_BOUND = 0.5e18; uint256 public constant STRATEGY_DELAY = 5 days; IController public immutable controller; IAddressProvider public immutable addressProvider; IVaultReserve public immutable reserve; modifier onlyPool() { require(msg.sender == pool, Error.UNAUTHORIZED_ACCESS); _; } modifier onlyPoolOrGovernance() { require( msg.sender == pool || _roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } modifier onlyPoolOrMaintenance() { require( msg.sender == pool || _roleManager().hasRole(Roles.MAINTENANCE, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } constructor(IController _controller) Authorization(_controller.addressProvider().getRoleManager()) { controller = _controller; IAddressProvider addressProvider_ = _controller.addressProvider(); addressProvider = addressProvider_; reserve = IVaultReserve(addressProvider_.getVaultReserve()); } function _initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) internal { require(_debtLimit <= ScaledMath.ONE, Error.INVALID_AMOUNT); require(_targetAllocation <= ScaledMath.ONE, Error.INVALID_AMOUNT); require(_bound <= MAX_DEVIATION_BOUND, Error.INVALID_AMOUNT); pool = _pool; _setConfig(_DEBT_LIMIT_KEY, _debtLimit); _setConfig(_TARGET_ALLOCATION_KEY, _targetAllocation); _setConfig(_BOUND_KEY, _bound); _setConfig(_RESERVE_FEE_KEY, _INITIAL_RESERVE_FEE); _setConfig(_STRATEGIST_FEE_KEY, _INITIAL_STRATEGIST_FEE); _setConfig(_PERFORMANCE_FEE_KEY, _INITIAL_PERFORMANCE_FEE); } /** * @notice Handles deposits from the liquidity pool */ function deposit() external payable override onlyPoolOrMaintenance { // solhint-disable-previous-line ordering _deposit(); } /** * @notice Withdraws specified amount of underlying from vault. * @dev If the specified amount exceeds idle funds, an amount of funds is withdrawn * from the strategy such that it will achieve a target allocation for after the * amount has been withdrawn. * @param amount Amount to withdraw. * @return `true` if successful. */ function withdraw(uint256 amount) external override onlyPoolOrGovernance returns (bool) { IStrategy strategy = getStrategy(); uint256 availableUnderlying_ = _availableUnderlying(); if (availableUnderlying_ < amount) { if (address(strategy) == address(0)) return false; uint256 allocated = strategy.balance(); uint256 requiredWithdrawal = amount - availableUnderlying_; if (requiredWithdrawal > allocated) return false; // compute withdrawal amount to sustain target allocation uint256 newTarget = (allocated - requiredWithdrawal).scaledMul(getTargetAllocation()); uint256 excessAmount = allocated - newTarget; strategy.withdraw(excessAmount); currentAllocated = _computeNewAllocated(currentAllocated, excessAmount); } else { uint256 allocatedUnderlying = 0; if (address(strategy) != address(0)) allocatedUnderlying = IStrategy(strategy).balance(); uint256 totalUnderlying = availableUnderlying_ + allocatedUnderlying + waitingForRemovalAllocated; uint256 totalUnderlyingAfterWithdraw = totalUnderlying - amount; _rebalance(totalUnderlyingAfterWithdraw, allocatedUnderlying); } _transfer(pool, amount); return true; } /** * @notice Withdraws all funds from vault and strategy and transfer them to the pool. */ function withdrawAll() external override onlyPoolOrGovernance { _withdrawAllFromStrategy(); _transfer(pool, _availableUnderlying()); } /** * @notice Withdraws specified amount of underlying from reserve to vault. * @dev Withdraws from reserve will cause a spike in pool exchange rate. * Pool deposits should be paused during this to prevent front running * @param amount Amount to withdraw. */ function withdrawFromReserve(uint256 amount) external override onlyGovernance { require(amount > 0, Error.INVALID_AMOUNT); require(IPausable(pool).isPaused(), Error.POOL_NOT_PAUSED); uint256 reserveBalance_ = reserve.getBalance(address(this), getUnderlying()); require(amount <= reserveBalance_, Error.INSUFFICIENT_BALANCE); reserve.withdraw(getUnderlying(), amount); } /** * @notice Activate the current strategy set for the vault. * @return `true` if strategy has been activated */ function activateStrategy() external onlyGovernance returns (bool) { return _activateStrategy(); } /** * @notice Deactivates a strategy. * @return `true` if strategy has been deactivated */ function deactivateStrategy() external onlyGovernance returns (bool) { return _deactivateStrategy(); } /** * @notice Initializes the vault's strategy. * @dev Bypasses the time delay, but can only be called if strategy is not set already. * @param strategy_ Address of the strategy. * @return `true` if successful. */ function initializeStrategy(address strategy_) external override onlyGovernance returns (bool) { require(currentAddresses[_STRATEGY_KEY] == address(0), Error.ADDRESS_ALREADY_SET); require(strategy_ != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); _setConfig(_STRATEGY_KEY, strategy_); _activateStrategy(); require(IStrategy(strategy_).strategist() != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); return true; } /** * @notice Prepare update of the vault's strategy (with time delay enforced). * @param newStrategy Address of the new strategy. * @return `true` if successful. */ function prepareNewStrategy(address newStrategy) external onlyGovernance returns (bool) { return _prepare(_STRATEGY_KEY, newStrategy, STRATEGY_DELAY); } /** * @notice Execute strategy update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New strategy address. */ function executeNewStrategy() external returns (address) { _executeDeadline(_STRATEGY_KEY); IStrategy strategy = getStrategy(); if (address(strategy) != address(0)) { _harvest(); strategy.shutdown(); strategy.withdrawAll(); // there might still be some balance left if the strategy did not // manage to withdraw all funds (e.g. due to locking) uint256 remainingStrategyBalance = strategy.balance(); if (remainingStrategyBalance > 0) { _strategiesWaitingForRemoval.set(address(strategy), remainingStrategyBalance); waitingForRemovalAllocated += remainingStrategyBalance; } } _deactivateStrategy(); currentAllocated = 0; totalDebt = 0; address newStrategy = pendingAddresses[_STRATEGY_KEY]; _setConfig(_STRATEGY_KEY, newStrategy); if (newStrategy != address(0)) { _activateStrategy(); } return newStrategy; } function resetNewStrategy() external onlyGovernance returns (bool) { return _resetAddressConfig(_STRATEGY_KEY); } /** * @notice Prepare update of performance fee (with time delay enforced). * @param newPerformanceFee New performance fee value. * @return `true` if successful. */ function preparePerformanceFee(uint256 newPerformanceFee) external onlyGovernance returns (bool) { require(newPerformanceFee <= MAX_PERFORMANCE_FEE, Error.INVALID_AMOUNT); return _prepare(_PERFORMANCE_FEE_KEY, newPerformanceFee); } /** * @notice Execute update of performance fee (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New performance fee. */ function executePerformanceFee() external returns (uint256) { return _executeUInt256(_PERFORMANCE_FEE_KEY); } function resetPerformanceFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_PERFORMANCE_FEE_KEY); } /** * @notice Prepare update of strategist fee (with time delay enforced). * @param newStrategistFee New strategist fee value. * @return `true` if successful. */ function prepareStrategistFee(uint256 newStrategistFee) external onlyGovernance returns (bool) { _checkFeesInvariant(getReserveFee(), newStrategistFee); return _prepare(_STRATEGIST_FEE_KEY, newStrategistFee); } /** * @notice Execute update of strategist fee (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New strategist fee. */ function executeStrategistFee() external returns (uint256) { uint256 newStrategistFee = _executeUInt256(_STRATEGIST_FEE_KEY); _checkFeesInvariant(getReserveFee(), newStrategistFee); return newStrategistFee; } function resetStrategistFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_STRATEGIST_FEE_KEY); } /** * @notice Prepare update of debt limit (with time delay enforced). * @param newDebtLimit New debt limit. * @return `true` if successful. */ function prepareDebtLimit(uint256 newDebtLimit) external onlyGovernance returns (bool) { return _prepare(_DEBT_LIMIT_KEY, newDebtLimit); } /** * @notice Execute update of debt limit (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New debt limit. */ function executeDebtLimit() external returns (uint256) { uint256 debtLimit = _executeUInt256(_DEBT_LIMIT_KEY); uint256 debtLimitAllocated = currentAllocated.scaledMul(debtLimit); if (totalDebt >= debtLimitAllocated) { _handleExcessDebt(); } return debtLimit; } function resetDebtLimit() external onlyGovernance returns (bool) { return _resetUInt256Config(_DEBT_LIMIT_KEY); } /** * @notice Prepare update of target allocation (with time delay enforced). * @param newTargetAllocation New target allocation. * @return `true` if successful. */ function prepareTargetAllocation(uint256 newTargetAllocation) external onlyGovernance returns (bool) { return _prepare(_TARGET_ALLOCATION_KEY, newTargetAllocation); } /** * @notice Execute update of target allocation (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New target allocation. */ function executeTargetAllocation() external returns (uint256) { uint256 targetAllocation = _executeUInt256(_TARGET_ALLOCATION_KEY); _deposit(); return targetAllocation; } function resetTargetAllocation() external onlyGovernance returns (bool) { return _resetUInt256Config(_TARGET_ALLOCATION_KEY); } /** * @notice Prepare update of reserve fee (with time delay enforced). * @param newReserveFee New reserve fee. * @return `true` if successful. */ function prepareReserveFee(uint256 newReserveFee) external onlyGovernance returns (bool) { _checkFeesInvariant(newReserveFee, getStrategistFee()); return _prepare(_RESERVE_FEE_KEY, newReserveFee); } /** * @notice Execute update of reserve fee (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New reserve fee. */ function executeReserveFee() external returns (uint256) { uint256 newReserveFee = _executeUInt256(_RESERVE_FEE_KEY); _checkFeesInvariant(newReserveFee, getStrategistFee()); return newReserveFee; } function resetReserveFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_RESERVE_FEE_KEY); } /** * @notice Prepare update of deviation bound for strategy allocation (with time delay enforced). * @param newBound New deviation bound for target allocation. * @return `true` if successful. */ function prepareBound(uint256 newBound) external onlyGovernance returns (bool) { require(newBound <= MAX_DEVIATION_BOUND, Error.INVALID_AMOUNT); return _prepare(_BOUND_KEY, newBound); } /** * @notice Execute update of deviation bound for strategy allocation (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New deviation bound. */ function executeBound() external returns (uint256) { uint256 bound = _executeUInt256(_BOUND_KEY); _deposit(); return bound; } function resetBound() external onlyGovernance returns (bool) { return _resetUInt256Config(_BOUND_KEY); } /** * @notice Withdraws an amount of underlying from the strategy to the vault. * @param amount Amount of underlying to withdraw. * @return True if successful withdrawal. */ function withdrawFromStrategy(uint256 amount) external onlyGovernance returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) return false; if (strategy.balance() < amount) return false; uint256 oldBalance = _availableUnderlying(); strategy.withdraw(amount); uint256 newBalance = _availableUnderlying(); currentAllocated -= newBalance - oldBalance; return true; } function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256) { (bool exists, uint256 allocated) = _strategiesWaitingForRemoval.tryGet(strategy); require(exists, Error.STRATEGY_DOES_NOT_EXIST); IStrategy strategy_ = IStrategy(strategy); strategy_.harvest(); uint256 withdrawn = strategy_.withdrawAll(); uint256 _waitingForRemovalAllocated = waitingForRemovalAllocated; if (withdrawn >= _waitingForRemovalAllocated) { waitingForRemovalAllocated = 0; } else { waitingForRemovalAllocated = _waitingForRemovalAllocated - withdrawn; } if (withdrawn > allocated) { uint256 profit = withdrawn - allocated; uint256 strategistShare = _shareFees(profit.scaledMul(getPerformanceFee())); if (strategistShare > 0) { _payStrategist(strategistShare, strategy_.strategist()); } allocated = 0; emit Harvest(profit, 0); } else { allocated -= withdrawn; } if (strategy_.balance() == 0) { _strategiesWaitingForRemoval.remove(address(strategy_)); } else { _strategiesWaitingForRemoval.set(address(strategy_), allocated); } return withdrawn; } function getStrategiesWaitingForRemoval() external view returns (address[] memory) { return _strategiesWaitingForRemoval.keysArray(); } /** * @notice Computes the total underlying of the vault: idle funds + allocated funds - debt * @return Total amount of underlying. */ function getTotalUnderlying() external view override returns (uint256) { uint256 availableUnderlying_ = _availableUnderlying(); if (address(getStrategy()) == address(0)) { return availableUnderlying_; } uint256 netUnderlying = availableUnderlying_ + currentAllocated + waitingForRemovalAllocated; if (totalDebt <= netUnderlying) return netUnderlying - totalDebt; return 0; } function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256) { return _strategiesWaitingForRemoval.get(strategy); } /** * @notice Withdraws all funds from strategy to vault. * @dev Harvests profits before withdrawing. Deactivates strategy after withdrawing. * @return `true` if successful. */ function withdrawAllFromStrategy() public onlyPoolOrGovernance returns (bool) { return _withdrawAllFromStrategy(); } /** * @notice Harvest profits from the vault's strategy. * @dev Harvesting adds profits to the vault's balance and deducts fees. * No performance fees are charged on profit used to repay debt. * @return `true` if successful. */ function harvest() public onlyPoolOrMaintenance returns (bool) { return _harvest(); } /** * @notice Returns the percentage of the performance fee that goes to the strategist. */ function getStrategistFee() public view returns (uint256) { return currentUInts256[_STRATEGIST_FEE_KEY]; } function getStrategy() public view override returns (IStrategy) { return IStrategy(currentAddresses[_STRATEGY_KEY]); } /** * @notice Returns the percentage of the performance fee which is allocated to the vault reserve */ function getReserveFee() public view returns (uint256) { return currentUInts256[_RESERVE_FEE_KEY]; } /** * @notice Returns the fee charged on a strategy's generated profits. * @dev The strategist is paid in LP tokens, while the remainder of the profit stays in the vault. * Default performance fee is set to 5% of harvested profits. */ function getPerformanceFee() public view returns (uint256) { return currentUInts256[_PERFORMANCE_FEE_KEY]; } /** * @notice Returns the allowed symmetric bound for target allocation (e.g. +- 5%) */ function getBound() public view returns (uint256) { return currentUInts256[_BOUND_KEY]; } /** * @notice The target percentage of total underlying funds to be allocated towards a strategy. * @dev this is to reduce gas costs. Withdrawals first come from idle funds and can therefore * avoid unnecessary gas costs. */ function getTargetAllocation() public view returns (uint256) { return currentUInts256[_TARGET_ALLOCATION_KEY]; } /** * @notice The debt limit that the total debt of a strategy may not exceed. */ function getDebtLimit() public view returns (uint256) { return currentUInts256[_DEBT_LIMIT_KEY]; } function getUnderlying() public view virtual override returns (address); function _activateStrategy() internal returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) return false; strategyActive = true; emit StrategyActivated(address(strategy)); _deposit(); return true; } function _harvest() internal returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) { return false; } strategy.harvest(); uint256 strategistShare = 0; uint256 allocatedUnderlying = strategy.balance(); uint256 amountAllocated = currentAllocated; uint256 currentDebt = totalDebt; if (allocatedUnderlying > amountAllocated) { // we made profits uint256 profit = allocatedUnderlying - amountAllocated; if (profit > currentDebt) { if (currentDebt > 0) { profit -= currentDebt; currentDebt = 0; } (profit, strategistShare) = _shareProfit(profit); } else { currentDebt -= profit; } emit Harvest(profit, 0); } else if (allocatedUnderlying < amountAllocated) { // we made a loss uint256 loss = amountAllocated - allocatedUnderlying; currentDebt += loss; // check debt limit and withdraw funds if exceeded uint256 debtLimit = getDebtLimit(); uint256 debtLimitAllocated = amountAllocated.scaledMul(debtLimit); if (currentDebt > debtLimitAllocated) { currentDebt = _handleExcessDebt(currentDebt); } emit Harvest(0, loss); } else { // nothing to declare return true; } totalDebt = currentDebt; currentAllocated = strategy.balance(); if (strategistShare > 0) { _payStrategist(strategistShare); } return true; } function _withdrawAllFromStrategy() internal returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) return false; _harvest(); uint256 oldBalance = _availableUnderlying(); strategy.withdrawAll(); uint256 newBalance = _availableUnderlying(); uint256 withdrawnAmount = newBalance - oldBalance; currentAllocated = _computeNewAllocated(currentAllocated, withdrawnAmount); _deactivateStrategy(); return true; } function _handleExcessDebt(uint256 currentDebt) internal returns (uint256) { uint256 underlyingReserves = reserve.getBalance(address(this), getUnderlying()); if (currentDebt > underlyingReserves) { _emergencyStop(underlyingReserves); } else if (reserve.canWithdraw(address(this))) { reserve.withdraw(getUnderlying(), currentDebt); currentDebt = 0; _deposit(); } return currentDebt; } function _handleExcessDebt() internal { uint256 currentDebt = totalDebt; uint256 newDebt = _handleExcessDebt(totalDebt); if (currentDebt != newDebt) { totalDebt = newDebt; } } /** * @notice Invest the underlying money in the vault after a deposit from the pool is made. * @dev After each deposit, the vault checks whether it needs to rebalance underlying funds allocated to strategy. * If no strategy is set then all deposited funds will be idle. */ function _deposit() internal { if (!strategyActive) return; uint256 allocatedUnderlying = getStrategy().balance(); uint256 totalUnderlying = _availableUnderlying() + allocatedUnderlying + waitingForRemovalAllocated; if (totalUnderlying == 0) return; _rebalance(totalUnderlying, allocatedUnderlying); } function _shareProfit(uint256 profit) internal returns (uint256, uint256) { uint256 totalFeeAmount = profit.scaledMul(getPerformanceFee()); if (_availableUnderlying() < totalFeeAmount) { getStrategy().withdraw(totalFeeAmount); } uint256 strategistShare = _shareFees(totalFeeAmount); return ((profit - totalFeeAmount), strategistShare); } function _shareFees(uint256 totalFeeAmount) internal returns (uint256) { uint256 strategistShare = totalFeeAmount.scaledMul(getStrategistFee()); uint256 reserveShare = totalFeeAmount.scaledMul(getReserveFee()); uint256 treasuryShare = totalFeeAmount - strategistShare - reserveShare; _depositToReserve(reserveShare); if (treasuryShare > 0) { _depositToTreasury(treasuryShare); } return strategistShare; } function _emergencyStop(uint256 underlyingReserves) internal { // debt limit exceeded: withdraw funds from strategy uint256 withdrawn = getStrategy().withdrawAll(); uint256 actualDebt = _computeNewAllocated(currentAllocated, withdrawn); if (reserve.canWithdraw(address(this))) { // check if debt can be covered with reserve funds if (underlyingReserves >= actualDebt) { reserve.withdraw(getUnderlying(), actualDebt); } else if (underlyingReserves > 0) { // debt can not be covered with reserves reserve.withdraw(getUnderlying(), underlyingReserves); } } // too much money lost, stop the strategy _deactivateStrategy(); } /** * @notice Deactivates a strategy. All positions of the strategy are exited. * @return `true` if strategy has been deactivated */ function _deactivateStrategy() internal returns (bool) { if (!strategyActive) return false; strategyActive = false; emit StrategyDeactivated(address(getStrategy())); return true; } function _payStrategist(uint256 amount) internal { _payStrategist(amount, getStrategy().strategist()); } function _payStrategist(uint256 amount, address strategist) internal virtual; function _transfer(address to, uint256 amount) internal virtual; function _depositToReserve(uint256 amount) internal virtual; function _depositToTreasury(uint256 amount) internal virtual; function _availableUnderlying() internal view virtual returns (uint256); function _computeNewAllocated(uint256 allocated, uint256 withdrawn) internal pure returns (uint256) { if (allocated > withdrawn) { return allocated - withdrawn; } return 0; } function _checkFeesInvariant(uint256 reserveFee, uint256 strategistFee) internal pure { require( reserveFee + strategistFee <= ScaledMath.ONE, "sum of strategist fee and reserve fee should be below 1" ); } function _rebalance(uint256 totalUnderlying, uint256 allocatedUnderlying) private returns (bool) { if (!strategyActive) return false; uint256 targetAllocation = getTargetAllocation(); IStrategy strategy = getStrategy(); uint256 bound = getBound(); uint256 target = totalUnderlying.scaledMul(targetAllocation); uint256 upperBound = targetAllocation == 0 ? 0 : targetAllocation + bound; upperBound = upperBound > ScaledMath.ONE ? ScaledMath.ONE : upperBound; uint256 lowerBound = bound > targetAllocation ? 0 : targetAllocation - bound; if (allocatedUnderlying > totalUnderlying.scaledMul(upperBound)) { // withdraw funds from strategy uint256 withdrawAmount = allocatedUnderlying - target; strategy.withdraw(withdrawAmount); currentAllocated = _computeNewAllocated(currentAllocated, withdrawAmount); } else if (allocatedUnderlying < totalUnderlying.scaledMul(lowerBound)) { // allocate more funds to strategy uint256 depositAmount = target - allocatedUnderlying; _transfer(address(strategy), depositAmount); currentAllocated += depositAmount; strategy.deposit(); } return true; } } // File contracts/vault/EthVault.sol pragma solidity 0.8.9; contract EthVault is Vault { using AddressProviderHelpers for IAddressProvider; address private constant _UNDERLYING = address(0); constructor(IController controller) Vault(controller) {} receive() external payable {} function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external virtual override initializer { _initialize(_pool, _debtLimit, _targetAllocation, _bound); } function getUnderlying() public pure override returns (address) { return _UNDERLYING; } function _transfer(address to, uint256 amount) internal override { payable(to).transfer(amount); } function _depositToReserve(uint256 amount) internal override { reserve.deposit{value: amount}(_UNDERLYING, amount); } function _depositToTreasury(uint256 amount) internal override { payable(addressProvider.getTreasury()).transfer(amount); } function _payStrategist(uint256 amount, address strategist) internal override { if (strategist == address(0)) return; ILiquidityPool(pool).depositFor{value: amount}(strategist, amount); } function _availableUnderlying() internal view override returns (uint256) { return address(this).balance; } }
Withdraws an amount of underlying from the strategy to the vault. amount Amount of underlying to withdraw. return True if successful withdrawal./
function withdrawFromStrategy(uint256 amount) external onlyGovernance returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) return false; if (strategy.balance() < amount) return false; uint256 oldBalance = _availableUnderlying(); strategy.withdraw(amount); uint256 newBalance = _availableUnderlying(); currentAllocated -= newBalance - oldBalance; return true; }
6,639,045
./partial_match/1/0xB5000059c584d04eCa43141fB13277F171B5839B/sources/dotApePublicRegistrarV2.sol
first 32 bytes, after the length prefix second 32 bytes final byte (first byte of the next 32 bytes)
function splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } return (v, r, s); }
3,965,997
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract Votable is Ownable{ // voter->bool mapping(address => bool) public voters; // voters count uint16 public votersCount = 0; // pid->proposal mapping(uint16 => Proposal) public proposals; // next pid, start with 10000 uint16 public nextPid = 10000; constructor() { // init owner as a voter voters[owner()] = true; votersCount++; emit AddVoter(owner()); } // struct of proposal struct Proposal { uint16 pid; uint16 count; bool done; bytes payload; // voter->bool mapping(address => bool) votes; } // events event OpenProposal(uint16 pid); event CloseProposal(uint16 pid); event DoneProposal(uint16 pid); event VoteProposal(uint16 pid, address voter); event AddVoter(address voter); event RemoveVoter(address voter); // modifiers modifier proposalExistAndNotDone(uint16 _pid){ require(proposals[_pid].pid == _pid, "Votable: proposal not exists"); require(!proposals[_pid].done, "Votable: proposal is done"); _; } modifier onlyVoters(){ require(voters[_msgSender()], "Votable: only voter can call"); _; } modifier onlySelf(){ require(_msgSender() == address(this), "Votable: only self can call"); _; } // for inheriting function _openProposal(bytes memory payload) internal{ uint16 pid = nextPid++; proposals[pid].pid = pid; proposals[pid].count = 0; proposals[pid].done = false; proposals[pid].payload = payload; emit OpenProposal(pid); } // vote function voteProposal(uint16 _pid) public onlyVoters proposalExistAndNotDone(_pid){ Proposal storage proposal = proposals[_pid]; require(!proposal.votes[_msgSender()], "Votable: duplicate voting is not allowed"); proposal.votes[_msgSender()] = true; proposal.count++; emit VoteProposal(_pid, _msgSender()); // judge _judge(proposal); } function _judge(Proposal storage _proposal) private{ if(_proposal.count > votersCount/2){ (bool success, ) = address(this).call(_proposal.payload); require(success, "Votable: call payload failed"); _proposal.done = true; emit DoneProposal(_proposal.pid); } } // hasVoted function hasVoted(uint16 _pid) public view returns(bool){ Proposal storage proposal = proposals[_pid]; require(proposal.pid == _pid, "Votable: proposal not exists"); return proposal.votes[_msgSender()]; } // translate proposal // function translateProposal(uint16 _pid) external view returns(bytes32, address, uint256){ // Proposal memory proposal = proposals[_pid]; // require(proposal.pid == _pid, "Votable: proposal not exists"); // return abi.decode(abi.encodePacked(bytes28(0), proposal.payload),(bytes32,address,uint256)); // } // onlySelf: match to proposals function addVoter(address _voter) external onlySelf{ require(!voters[_voter], "Votable: this address is already a voter"); voters[_voter] = true; votersCount++; emit AddVoter(_voter); } function removeVoter(address _voter) external onlySelf{ require(voters[_voter], "Votable: this address is not a voter"); require(_voter != owner(), "Votable: owner can not be removed"); voters[_voter] = false; votersCount--; emit RemoveVoter(_voter); } // onlyOwner // open proposals function openAddVoterProposal(address _voter) external onlyOwner{ _openProposal(abi.encodeWithSignature("addVoter(address)",_voter)); } function openRemoveVoterProposal(address _voter) external onlyOwner{ _openProposal(abi.encodeWithSignature("removeVoter(address)",_voter)); } // close proposal function closeProposal(uint16 _pid) external proposalExistAndNotDone(_pid) onlyOwner{ proposals[_pid].done = true; emit CloseProposal(_pid); } }
onlySelf: match to proposals
function addVoter(address _voter) external onlySelf{ require(!voters[_voter], "Votable: this address is already a voter"); voters[_voter] = true; votersCount++; emit AddVoter(_voter); }
2,494,182
./partial_match/1/0xB497C15265107783E6309bA7f73817f0578a72B4/sources/src/WERC721.sol
The descriptive name for a collection of NFTs in this contract. We are returning the value of `name()` on the underlying ERC721 contract for parity between the derivatives and the actual assets. return string The descriptive name for a collection of NFTs in this contract./
function name() external view returns (string memory) { return collection().name(); }
4,040,619
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA/CONTROL VARIABLES */ /********************************************************************************************/ struct Airlines { bool isRegistered; bool isOperational; } struct Insurance { address passenger; uint256 amount; } struct Fund { uint256 amount; } struct Voters { bool status; } address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => uint256) private authorizedCaller; address[] multiCalls = new address[](0); mapping(address => Airlines) airlines; // mapping address to struct which holds registered airlines. mapping(address => Insurance) insurance; // Airline address maps to struct mapping(address => uint256) balances; mapping(address => Fund) fund; mapping(address => uint256) private voteCount; mapping(address => Voters) voters; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AuthorizedContract(address authContract); event DeAuthorizedContract(address authContract); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires an Airline to be registered */ modifier requireAirlineRegistered(address airline) { require(airlines[airline].isRegistered, "Airline is not registered"); _; } /** * @dev Modifier that requires an Airline is not registered yet */ modifier requireAirlineIsNotRegistered(address airline) { require(!airlines[airline].isRegistered, "Airline is already registered."); _; } /** * @dev Modifier that requires the "ContractAddress" account to be authorized */ /* modifier requireContractAddressAuthorized(address _contractAddress) { require( authorizedContracts[_contractAddress], "ContractAddress is not authorized" ); _; } */ /********************************************************************************************/ /* 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; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ // ------------------- Get and Set function for multiCalls ------------------------- function setmultiCalls(address account) private { multiCalls.push(account); } function multiCallsLength() external view requireIsOperational returns(uint256){ return multiCalls.length; } //----------------- Set and Get function for Airline struct ------------------------------ function getAirlineOperatingStatus(address account) external view requireIsOperational returns(bool){ return airlines[account].isOperational; } function setAirlineOperatingStatus(address account, bool status) external requireIsOperational { airlines[account].isOperational = status; } function getAirlineRegistrationStatus(address account) external view requireIsOperational returns(bool){ return airlines[account].isRegistered; } function getVoteCounter(address account) external view requireIsOperational returns(uint){ return voteCount[account]; } function resetVoteCounter(address account) external requireIsOperational{ delete voteCount[account]; } function getVoterStatus(address voter) external view requireIsOperational returns(bool){ return voters[voter].status; } function addVoters(address voter) external{ voters[voter] = Voters({ status: true }); } function addVoterCounter(address airline, uint count) external{ uint vote = voteCount[airline]; voteCount[airline] = vote.add(count); } // ---------------------------- Insurance registration -------------------------- function registerInsurance(address airline, address passenger, uint256 amount) external requireIsOperational{ insurance[airline] = Insurance({ passenger: passenger, amount: amount }); uint256 getFund = fund[airline].amount; fund[airline].amount = getFund.add(amount); } //-----------------------------Fund recording ------------------------- function fundAirline(address airline, uint256 amount) external{ fund[airline] = Fund({ amount: amount }); } function getAirlineFunding(address airline) external view returns(uint256){ return fund[airline].amount; } function authorizeCaller ( address contractAddress ) external requireContractOwner { authorizedCaller[contractAddress] = 1; emit AuthorizedContract(contractAddress); } function deauthorizeContract ( address contractAddress ) external requireContractOwner { delete authorizedCaller[contractAddress]; emit DeAuthorizedContract(contractAddress); } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address account, bool _isOperational ) external requireIsOperational { // isRegistered is Always true for a registered airline // isOperational is only true when the airline has submited funding of 10 ether airlines[account] = Airlines({ isRegistered: true, isOperational: _isOperational }); setmultiCalls(account); } /** * @dev Check if an airline is registered * * @return A bool that indicates if the airline is registered */ function isAirline ( address account ) external view returns(bool) { require(account != address(0), "'account' must be a valid address."); return airlines[account].isRegistered; } /** * @dev Credits payouts to insurees */ function creditInsurees ( address airline, address passenger, uint256 amount ) external requireIsOperational { // Get expected amount to be credited uint256 required_amount =insurance[airline].amount.mul(3).div(2); require(insurance[airline].passenger == passenger, "Passenger is not insured"); require(required_amount == amount, "The amount to be credited is not as espected"); require((passenger != address(0)) && (airline != address(0)), "'accounts' must be valid address."); // Store amount to be credited in passenger balance balances[passenger] = amount; } function withdraw ( address passenger ) external requireIsOperational returns(uint256) { uint256 withdraw_cash = balances[passenger]; delete balances[passenger]; return withdraw_cash; } function getInsuredPassenger_amount(address airline) external view requireIsOperational returns(address, uint256){ return (insurance[airline].passenger,insurance[airline].amount); } function getPassengerCredit(address passenger) external view requireIsOperational returns(uint256){ return balances[passenger]; } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } }
----------------- Set and Get function for Airline struct ------------------------------
function getAirlineOperatingStatus(address account) external view requireIsOperational returns(bool){ return airlines[account].isOperational; }
12,546,863
./partial_match/1/0xB0a3494E876Cd066CB8dc9d16A312Cc11Df4d20A/sources/OxOMixerPool.sol
Gets the lates ring index for `amountToken` amountToken The amount of `token` in the ring
function getCurrentRingIndex(uint256 amountToken) external view returns (uint256) { amountCheck(amountToken); return ringsNumber[amountToken]; }
15,528,744
// SPDX-License-Identifier:MIT pragma solidity ^0.8.0; pragma abicoder v2; contract MultiSigWallet{ address[] public owners; event TxApproved(address indexed approvedBy, uint indexed index_, address receiver, uint amount); uint public limits; // ["0x5B38Da6a701c568545dCfcB03FcB875f56beddC4", "0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2", "0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db"] 0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db constructor(address[] memory _owners) { bool senderInList=false; for (uint i=0; i<_owners.length; i++) { if (_owners[i]==msg.sender) { senderInList=true; } } if (senderInList==false) { owners=_owners; owners.push(msg.sender); limits=((owners.length*2*10**18)/3); }else{ owners=_owners; limits=((owners.length*2*10**18)/3); } } modifier isOwner { bool owner = false; for (uint i=0; i<owners.length; i++){ if (owners[i] == msg.sender) { owner=true; } } require(owner==true, "You're not a signatory of this contract."); _; } struct Transaction { uint amount; address payable receiver; uint approvals; bool hasBeenSent; uint id; } // Approval maps an owner to the id of a transaction which maps to True/False, depending on whether a user has approved a given transaction or not. mapping(address=>mapping(uint=>bool)) public approvals; Transaction[] public txRequests; // Transaction list // Performs a transfer from the multisig wallet. which in turn requires two-third of signatories to approve in order to complete. function makeTransfer(address payable _to, uint _amount) public isOwner{ require(address(this).balance>=_amount, "Insufficient balance!"); uint _index=txRequests.length; txRequests.push(Transaction(_amount, _to, 1, false, _index)); approvals[msg.sender][_index]=true; } // Owners can approve Transactions from this function. // It also checks to confirm if up to two-third of the owners have approved the transaction in order to confirm said transaction. // Also makes sure an owner can not approve a transaction twice. function approveTransfer(uint _index) public isOwner{ if (_index>=txRequests.length) return; require(approvals[msg.sender][_index]==false); require(txRequests[_index].hasBeenSent==false); approvals[msg.sender][_index]=true; txRequests[_index].approvals+=1; uint count=(txRequests[_index].approvals)*10**18; if (count>=limits) { txRequests[_index].receiver.transfer(txRequests[_index].amount); txRequests[_index].hasBeenSent=true; } emit TxApproved(msg.sender, _index, txRequests[_index].receiver, txRequests[_index].amount); } // Deposit Function anybody can deposit to this contract using deposit() function deposit() public payable returns(uint) {} // Get MultiSig Wallet balance. Only owners can access this function function getBalance() public view isOwner returns(uint) { return address(this).balance; } // Returns List of Transactions function getTxRequests() public view returns (Transaction[] memory){ return txRequests; } }
Returns List of Transactions
function getTxRequests() public view returns (Transaction[] memory){ return txRequests; }
12,664,973
./full_match/5/0x67Ee3EAD8A0E345496150bA436349bFc673E90f9/sources/contracts/lib/Cryptography.sol
The primary hash method for Fuel. data The bytes input data. return The returned hash result.
function hash(bytes memory data) internal pure returns (bytes32) { return sha256(data); }
11,635,403
./full_match/1/0x33dcCC62Ec75b93fB2bCE5d012533A9D9F53f5C3/sources/home/konstantinovv/source/pollen/investment-fund-dao/contracts/Stem_v1.sol
Returns the block when token transfers get allowed ("virtual" to facilitate testing)/
function unlockBlock() internal virtual pure returns(uint) { return UNLOCK_BLOCK; }
8,479,462
// "SPDX-License-Identifier: Apache-2.0" pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "../../Core/Core.sol"; import "../../Core/FixedPointMath.sol"; import "./ICECEngine.sol"; import "./CECSTF.sol"; import "./CECPOF.sol"; /** * @title CECEngine * @notice Inherits from BaseEngine by implementing STFs, POFs according to the ACTUS standard for a CEC contract * @dev All numbers except unix timestamp are represented as multiple of 10 ** 18 * inputs have to be multiplied by 10 ** 18, outputs have to multplied by 10 ** -18 */ contract CECEngine is Core, CECSTF, CECPOF, ICECEngine { using SignedSafeMath for int; using FixedPointMath for int; function contractType() external pure override returns (ContractType) { return ContractType.CEC; } /** * Applys an event to the current state of a contract and returns the resulting contract state. * @param terms terms of the contract * @param state current state of the contract * @param _event event to be applied to the contract state * @param externalData external data needed for STF evaluation (e.g. rate for RR events) * @return the resulting contract state */ function computeStateForEvent( CECTerms calldata terms, CECState calldata state, bytes32 _event, bytes calldata externalData ) external pure override returns (CECState memory) { return stateTransitionFunction( terms, state, _event, externalData ); } /** * Evaluates the payoff for an event under the current state of the contract. * @param terms terms of the contract * @param state current state of the contract * @param _event event for which the payoff should be evaluated * @param externalData external data needed for POF evaluation (e.g. fxRate) * @return the payoff of the event */ function computePayoffForEvent( CECTerms calldata terms, CECState calldata state, bytes32 _event, bytes calldata externalData ) external pure override returns (int256) { // // if alternative settlementCurrency is set then apply fxRate to payoff // if (terms.settlementCurrency != address(0) && terms.currency != terms.settlementCurrency) { // return payoffFunction( // terms, // state, // _event, // externalData // ).fixedMul(int256(externalData)); // } return payoffFunction( terms, state, _event, externalData ); } /** * @notice Initialize contract state space based on the contract terms. * @param terms terms of the contract * @return initial state of the contract */ function computeInitialState(CECTerms calldata terms) external pure override returns (CECState memory) { CECState memory state; state.contractPerformance = ContractPerformance.PF; state.statusDate = terms.statusDate; state.maturityDate = terms.maturityDate; return state; } /** * @notice Computes a schedule segment of non-cyclic contract events based on the contract terms * and the specified timestamps. * @param terms terms of the contract * @param segmentStart start timestamp of the segment * @param segmentEnd end timestamp of the segement * @return segment of the non-cyclic schedule */ function computeNonCyclicScheduleSegment( CECTerms calldata terms, uint256 segmentStart, uint256 segmentEnd ) external pure override returns (bytes32[] memory) { bytes32[MAX_EVENT_SCHEDULE_SIZE] memory events; uint16 index; // maturity event if (isInSegment(terms.maturityDate, segmentStart, segmentEnd) == true) { events[index] = encodeEvent(EventType.MD, terms.maturityDate); index++; } // remove null entries from returned array bytes32[] memory schedule = new bytes32[](index); for (uint256 i = 0; i < index; i++) { schedule[i] = events[i]; } return schedule; } /** * @notice Computes a schedule segment of cyclic contract events based on the contract terms * and the specified timestamps. * param terms terms of the contract * param segmentStart start timestamp of the segment * param segmentEnd end timestamp of the segement * param eventType eventType of the cyclic schedule * @return event schedule segment */ function computeCyclicScheduleSegment( CECTerms calldata /* terms */, uint256 /* segmentStart */, uint256 /* segmentEnd */, EventType /* eventType */ ) external pure override returns (bytes32[] memory) { bytes32[] memory schedule = new bytes32[](0); return schedule; } /** * @notice Computes the next non-cyclic contract events based on the contract terms * and the timestamp on which the prev. event occured. * @dev Assumes that non-cyclic events of the same event type have a unique schedule time * @param terms terms of the contract * @param lastNonCyclicEvent last non-cyclic event * @return next non-cyclic event */ function computeNextNonCyclicEvent( CECTerms calldata terms, bytes32 lastNonCyclicEvent ) external pure override returns (bytes32) { (EventType lastEventType, uint256 lastScheduleTime) = decodeEvent(lastNonCyclicEvent); EventType eventTypeNextEvent; uint256 scheduleTimeNextEvent; // EventTypes ordered after epoch offset - so we don't have make an additional epochOffset check // maturity event if ( // date for event has to be set in terms and date of event can be in the past (terms.maturityDate != 0 && (lastScheduleTime <= terms.maturityDate)) // date for event has to come before previous candidate for the next event // && (scheduleTimeNextEvent == 0 || terms.maturityDate < scheduleTimeNextEvent) // avoid endless loop by requiring that the event is not the lastNonCyclicEvent && (lastScheduleTime != terms.maturityDate || lastEventType != EventType.MD) ) { eventTypeNextEvent = EventType.MD; scheduleTimeNextEvent = terms.maturityDate; } return encodeEvent(eventTypeNextEvent, scheduleTimeNextEvent); } /** * @notice Computes a schedule segment of cyclic contract events based on the contract terms * and the specified timestamps. * param terms terms of the contract * param lastScheduleTime last occurrence of cyclic event * param eventType eventType of the cyclic schedule * @return event schedule segment */ function computeNextCyclicEvent( CECTerms calldata /* terms */, uint256 /* lastScheduleTime */, EventType /* eventType */ ) external pure override returns(bytes32) { return bytes32(0); } /** * @notice Verifies that the provided event is still scheduled under the terms, the current state of the * contract and the current state of the underlying. * param _event event for which to check if its still scheduled * param terms terms of the contract * param state current state of the contract * param underlyingState state of the underlying (empty state object if non-existing) * @return boolean indicating whether event is still scheduled */ function isEventScheduled( bytes32 /* _event */, CECTerms calldata /* terms */, CECState calldata /* state */, UnderlyingState calldata /* underlyingState */ ) external pure override returns (bool) { // no contract performance for CEC return true; } /** * @notice Implements abstract method which is defined in BaseEngine. * Applies an event to the current state of the contract and returns the resulting state. * The inheriting Engine contract has to map the events type to the designated STF. * @param terms terms of the contract * @param state current state of the contract * @param _event event for which to evaluate the next state for * @param externalData external data needed for STF evaluation (e.g. rate for RR events) * @return the resulting contract state */ function stateTransitionFunction( CECTerms memory terms, CECState memory state, bytes32 _event, bytes calldata externalData ) internal pure returns (CECState memory) { (EventType eventType, uint256 scheduleTime) = decodeEvent(_event); if (eventType == EventType.EXE) return STF_CEC_EXE(terms, state, scheduleTime, externalData); if (eventType == EventType.MD) return STF_CEC_MD(terms, state, scheduleTime, externalData); if (eventType == EventType.ST) return STF_CEC_ST(terms, state, scheduleTime, externalData); if (eventType == EventType.CE) return STF_CEC_CE(terms, state, scheduleTime, externalData); revert("CECEngine.stateTransitionFunction: ATTRIBUTE_NOT_FOUND"); } /** * @notice Implements abstract method which is defined in BaseEngine. * Computes the payoff for an event under the current state of the contract. * The inheriting Engine contract has to map the events type to the designated POF. * @param terms terms of the contract * @param state current state of the contract * @param _event event for which the payoff should be evaluated * @param externalData external data needed for POF evaluation (e.g. fxRate) * @return the payoff of the event */ function payoffFunction( CECTerms memory terms, CECState memory state, bytes32 _event, bytes calldata externalData ) internal pure returns (int256) { (EventType eventType, uint256 scheduleTime) = decodeEvent(_event); if (eventType == EventType.CE) return 0; if (eventType == EventType.EXE) return 0; if (eventType == EventType.ST) return POF_CEC_ST(terms, state, scheduleTime, externalData); if (eventType == EventType.MD) return 0; revert("CECEngine.payoffFunction: ATTRIBUTE_NOT_FOUND"); } }
Implements abstract method which is defined in BaseEngine. Computes the payoff for an event under the current state of the contract. The inheriting Engine contract has to map the events type to the designated POF. terms terms of the contract state current state of the contract _event event for which the payoff should be evaluated externalData external data needed for POF evaluation (e.g. fxRate) return the payoff of the event/
function payoffFunction( CECTerms memory terms, CECState memory state, bytes32 _event, bytes calldata externalData ) internal pure returns (int256) { (EventType eventType, uint256 scheduleTime) = decodeEvent(_event); if (eventType == EventType.CE) return 0; if (eventType == EventType.EXE) return 0; if (eventType == EventType.ST) return POF_CEC_ST(terms, state, scheduleTime, externalData); if (eventType == EventType.MD) return 0; revert("CECEngine.payoffFunction: ATTRIBUTE_NOT_FOUND"); }
5,381,342
./partial_match/42/0xc11AC37EfA2ED218D0B249B8E23c4eb584B41BA6/sources/Dollar.sol
overridable for testing
function usdc() public view returns (address) { return Constants.getUsdc(); }
8,845,138
./full_match/80001/0x99c0F08513545a1C407cb5787B961B8C083Fd76a/sources/nftstakingcontract.sol
User has reward to claimStakes Time of last update should be resetReset unclaimed rewards = 0Transfer rewards
function claimReward() external { uint256 rewards = calculateRewards(msg.sender) + stakers[msg.sender].unclaimedRewards; require(rewards > 0, "You have no rewards to claim"); stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = 0; rewardsToken.safeTransferFrom(address(this), msg.sender, rewards); }
5,623,549
// SPDX-License-Identifier: MIT pragma solidity 0.5.17; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; /** * @title RariGovernanceToken * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @notice RariGovernanceToken is the contract behind the Rari Governance Token (RGT), an ERC20 token accounting for the ownership of Rari Stable Pool, Yield Pool, and Ethereum Pool. */ contract RariGovernanceToken is Initializable, ERC20, ERC20Detailed, ERC20Burnable, ERC20Pausable { using SafeERC20 for IERC20; /** * @dev Initializer that reserves 8.75 million RGT for liquidity mining and 1.25 million RGT to the team/advisors/etc. */ function initialize(address distributor, address vesting) public initializer { ERC20Detailed.initialize("Rari Governance Token", "RGT", 18); ERC20Pausable.initialize(msg.sender); _mint(distributor, 8750000 * (10 ** uint256(decimals()))); _mint(vesting, 1250000 * (10 ** uint256(decimals()))); } /** * @dev Boolean indicating if this RariFundToken contract has been deployed at least `v1.4.0` or upgraded to at least `v1.4.0`. */ bool private upgraded1; /** * @dev Boolean indicating if this RariFundToken contract has been deployed at least `v1.4.0` or upgraded to at least `v1.4.0`. */ bool private upgraded2; /** * @dev Upgrades RariGovernanceToken from `v1.3.0` to `v1.4.0`. */ function upgrade2() external onlyPauser { require(!upgraded2, "Already upgraded."); _mint(msg.sender, 2600000 * (10 ** uint256(decimals()))); upgraded2 = true; } /** * @dev Forwards tokens accidentally sent to this contract to the specified address. * At no point in time should this contract hold any tokens. * @param erc20Contract The ERC20 contract address of the token to forward. * @param to The destination address to which the funds will be forwarded. * @param amount Amount of tokens to forward. */ function sweepLostFunds(address erc20Contract, address to, uint256 amount) external onlyPauser { IERC20(erc20Contract).safeTransfer(to, 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) { _transfer(_msgSender(), recipient, amount); _moveDelegates(delegates[_msgSender()], delegates[recipient], safe96(amount, "RGT::transfer: amount exceeds 96 bits")); 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); _moveDelegates(delegates[sender], delegates[recipient], safe96(amount, "RGT::transferFrom: amount exceeds 96 bits")); _approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "RGT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "RGT::delegateBySig: invalid nonce"); require(now <= expiry, "RGT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "RGT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(balanceOf(delegator), "RGT::_delegate: balance exceeds 96 bits"); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "RGT::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "RGT::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "RGT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.5.17; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./RariGovernanceToken.sol"; /** * @title RariGovernanceTokenVestingV2 * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @notice RariGovernanceTokenVestingV2 distributes private RGT (Rari Governance Token) allocations to accounts with a vesting schedule. */ contract RariGovernanceTokenVestingV2 is Initializable, Ownable { using SafeMath for uint256; /** * @dev Initializer that configures private vesting start and end timestamps. */ function initialize(uint256 _privateVestingStartTimestamp) public initializer { Ownable.initialize(msg.sender); privateVestingStartTimestamp = _privateVestingStartTimestamp; privateVestingEndTimestamp = _privateVestingStartTimestamp.add(PRIVATE_VESTING_PERIOD); } /** * @dev The RariGovernanceToken contract. */ RariGovernanceToken rariGovernanceToken; /** * @dev Sets the RariGovernanceToken distributed by ths RariGovernanceTokenDistributor. * @param governanceToken The new RariGovernanceToken contract. */ function setGovernanceToken(RariGovernanceToken governanceToken) external onlyOwner { require(address(governanceToken) != address(0), "New governance token contract cannot be the zero address."); rariGovernanceToken = governanceToken; } /** * @notice Length in seconds of the distribution period. */ uint256 public privateVestingStartTimestamp; /** * @notice Length in seconds of the distribution period. */ uint256 public constant PRIVATE_VESTING_PERIOD = 3 * 365 * 86400; /** * @notice Length in seconds of the distribution period. */ uint256 public privateVestingEndTimestamp; /** * @dev Sets the `amount` of RGT privately allocated to `holder`. * @param holder The new RariGovernanceToken contract. */ function setPrivateRgtAllocation(address holder, uint256 amount) external onlyOwner { require(holder != address(0), "Holder cannot be the zero address."); require(amount >= _privateRgtClaimed[holder], "Allocation amount must be greater than or equal to the amount claimed by this holder."); _privateRgtAllocated = _privateRgtAllocated.sub(privateRgtAllocations[holder]).add(amount); require(_privateRgtAllocated <= FINAL_PRIVATE_RGT_ALLOCATION, "Total RGT privately allocated cannot exceed the final private RGT allocation."); privateRgtAllocations[holder] = amount; } /** * @notice Total and final quantity of all RGT to be privately allocated. */ uint256 public constant FINAL_PRIVATE_RGT_ALLOCATION = 42000e18; /** * @notice Current quantity of RGT that has been privately allocated. */ uint256 private _privateRgtAllocated; /** * @dev Maps addresses to private RGT distribution quantities. */ mapping(address => uint256) public privateRgtAllocations; /** * @dev Maps addresses to claimed quantities of private RGT allocations. */ mapping(address => uint256) private _privateRgtClaimed; /** * @dev Event emitted when `claimed` RGT is claimed by `holder`. */ event PrivateClaim(address holder, uint256 claimed); /** * @notice Returns the amount of RGT currently distributed to a given `holder`. * @param timestamp The timestamp at which to check data. * @param holder The holder of the unclaimed RGT allocated privately. * @return The quantity of distributed RGT. */ function getDistributedPrivateRgt(uint256 timestamp, address holder) public view returns (uint256) { if (timestamp <= privateVestingStartTimestamp) return 0; if (timestamp >= privateVestingEndTimestamp) return privateRgtAllocations[holder]; return privateRgtAllocations[holder].mul(timestamp.sub(privateVestingStartTimestamp)).div(PRIVATE_VESTING_PERIOD); } /** * @notice Returns the quantity of unclaimed RGT allocated privately to `holder`. * @param holder The holder of the unclaimed RGT allocated privately. * @return The quantity of unclaimed RGT. */ function getUnclaimedPrivateRgt(address holder) public view returns (uint256) { return getDistributedPrivateRgt(block.timestamp, holder).sub(_privateRgtClaimed[holder]); } /** * @notice Internal function to claim `amount` unclaimed RGT allocated privately to `holder` (without validating `amount`). * @param holder The holder of the unclaimed RGT allocated privately. * @param amount The amount of RGT to claim. */ function _claimPrivateRgt(address holder, uint256 amount) internal { _privateRgtClaimed[holder] = _privateRgtClaimed[holder].add(amount); require(rariGovernanceToken.transfer(holder, amount), "Failed to transfer RGT from vesting reserve."); emit PrivateClaim(holder, amount); } /** * @notice Claims `amount` unclaimed RGT allocated privately to `msg.sender`. * @param amount The amount of RGT to claim. */ function claimPrivateRgt(uint256 amount) external { uint256 unclaimedRgt = getUnclaimedPrivateRgt(msg.sender); require(amount <= unclaimedRgt, "You cannot claim this much RGT (yet)."); _claimPrivateRgt(msg.sender, amount); } /** * @notice Claims all unclaimed RGT allocated privately to `msg.sender`. */ function claimAllPrivateRgt() external { uint256 unclaimedRgt = getUnclaimedPrivateRgt(msg.sender); require(unclaimedRgt > 0, "Unclaimed RGT allocated privately not greater than 0."); _claimPrivateRgt(msg.sender, unclaimedRgt); } /** * @dev Forwards RGT to a new RariGovernanceTokenVesting contract. * @param newContract The new RariGovernanceTokenVesting contract. * @param amount Amount of RGT to forward to the new contract. */ function upgrade(address newContract, uint256 amount) external onlyOwner { rariGovernanceToken.transfer(newContract, amount); } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "../Roles.sol"; contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } 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); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; import "../access/roles/PauserRole.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Initializable, 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. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _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()); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/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 {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/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). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./ERC20.sol"; import "../../lifecycle/Pausable.sol"; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } 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); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
Sets the `amount` of RGT privately allocated to `holder`. holder The new RariGovernanceToken contract./
function setPrivateRgtAllocation(address holder, uint256 amount) external onlyOwner { require(holder != address(0), "Holder cannot be the zero address."); require(amount >= _privateRgtClaimed[holder], "Allocation amount must be greater than or equal to the amount claimed by this holder."); _privateRgtAllocated = _privateRgtAllocated.sub(privateRgtAllocations[holder]).add(amount); require(_privateRgtAllocated <= FINAL_PRIVATE_RGT_ALLOCATION, "Total RGT privately allocated cannot exceed the final private RGT allocation."); privateRgtAllocations[holder] = amount; }
5,952,807
./full_match/84531/0xce6525630B6cBC45F7DdC204a59022d8E39f560E/sources/node_modules/_zoralabs/openzeppelin-contracts-upgradeable/contracts/token/ERC1155/ERC1155Upgradeable.sol
See {IERC1155-safeBatchTransferFrom}./
function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { if (from != _msgSender() && !isApprovedForAll(from, _msgSender())) { revert ERC1155_CALLER_IS_NOT_TOKEN_OWNER_OR_APPROVED(); } _safeBatchTransferFrom(from, to, ids, amounts, data); }
11,522,777
./full_match/97/0xFbb952EF8435CA572306d3613d81B27E074F3a17/sources/contracts/core/DrawBuffer.sol
@inheritdoc IDrawBuffer
function pushDraw(IDrawBeacon.Draw memory _draw) external override onlyManagerOrOwner returns (uint32) { return _pushDraw(_draw); }
3,273,520
//Address: 0xc72ed4445b3fe9f0863106e344e241530d338906 //Contract name: MallcoinToken //Balance: 0 Ether //Verification Date: 2/20/2018 //Transacion Count: 1084 // CODE STARTS HERE pragma solidity ^0.4.18; 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) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Authorizable { mapping(address => bool) authorizers; modifier onlyAuthorized { require(isAuthorized(msg.sender)); _; } function Authorizable() public { authorizers[msg.sender] = true; } function isAuthorized(address _addr) public constant returns(bool) { require(_addr != address(0)); bool result = bool(authorizers[_addr]); return result; } function addAuthorized(address _addr) external onlyAuthorized { require(_addr != address(0)); authorizers[_addr] = true; } function delAuthorized(address _addr) external onlyAuthorized { require(_addr != address(0)); require(_addr != msg.sender); //authorizers[_addr] = false; delete authorizers[_addr]; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; //modifier onlyPayloadSize(uint size) { // require(msg.data.length < size + 4); // _; //} function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { //requeres in FrozenToken //require(_to != address(0)); //require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { //requires in FrozenToken //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; } function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } 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; } } } contract FrozenToken is StandardToken, Ownable { mapping(address => bool) frozens; mapping(address => uint256) frozenTokens; event FrozenAddress(address addr); event UnFrozenAddress(address addr); event FrozenTokenEvent(address addr, uint256 amount); event UnFrozenTokenEvent(address addr, uint256 amount); modifier isNotFrozen() { require(frozens[msg.sender] == false); _; } function frozenAddress(address _addr) onlyOwner public returns (bool) { require(_addr != address(0)); frozens[_addr] = true; FrozenAddress(_addr); return frozens[_addr]; } function unFrozenAddress(address _addr) onlyOwner public returns (bool) { require(_addr != address(0)); delete frozens[_addr]; //frozens[_addr] = false; UnFrozenAddress(_addr); return frozens[_addr]; } function isFrozenByAddress(address _addr) public constant returns(bool) { require(_addr != address(0)); bool result = bool(frozens[_addr]); return result; } function balanceFrozenTokens(address _addr) public constant returns(uint256) { require(_addr != address(0)); uint256 result = uint256(frozenTokens[_addr]); return result; } function balanceAvailableTokens(address _addr) public constant returns(uint256) { require(_addr != address(0)); uint256 frozen = uint256(frozenTokens[_addr]); uint256 balance = uint256(balances[_addr]); require(balance >= frozen); uint256 result = balance.sub(frozen); return result; } function frozenToken(address _addr, uint256 _amount) onlyOwner public returns(bool) { require(_addr != address(0)); require(_amount > 0); uint256 balance = uint256(balances[_addr]); require(balance >= _amount); frozenTokens[_addr] = frozenTokens[_addr].add(_amount); FrozenTokenEvent(_addr, _amount); return true; } function unFrozenToken(address _addr, uint256 _amount) onlyOwner public returns(bool) { require(_addr != address(0)); require(_amount > 0); require(frozenTokens[_addr] >= _amount); frozenTokens[_addr] = frozenTokens[_addr].sub(_amount); UnFrozenTokenEvent(_addr, _amount); return true; } function transfer(address _to, uint256 _value) isNotFrozen() public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); uint256 balance = balances[msg.sender]; uint256 frozen = frozenTokens[msg.sender]; uint256 availableBalance = balance.sub(frozen); require(availableBalance >= _value); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) isNotFrozen() public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); uint256 balance = balances[_from]; uint256 frozen = frozenTokens[_from]; uint256 availableBalance = balance.sub(frozen); require(availableBalance >= _value); return super.transferFrom(_from ,_to, _value); } } contract MallcoinToken is FrozenToken, Authorizable { string public constant name = "Mallcoin Token"; string public constant symbol = "MLC"; uint8 public constant decimals = 18; uint256 public MAX_TOKEN_SUPPLY = 250000000 * 1 ether; event CreateToken(address indexed to, uint256 amount); event CreateTokenByAtes(address indexed to, uint256 amount, string data); modifier onlyOwnerOrAuthorized { require(msg.sender == owner || isAuthorized(msg.sender)); _; } function createToken(address _to, uint256 _amount) onlyOwnerOrAuthorized public returns (bool) { require(_to != address(0)); require(_amount > 0); require(MAX_TOKEN_SUPPLY >= totalSupply_ + _amount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); // KYC frozens[_to] = true; FrozenAddress(_to); CreateToken(_to, _amount); Transfer(address(0), _to, _amount); return true; } function createTokenByAtes(address _to, uint256 _amount, string _data) onlyOwnerOrAuthorized public returns (bool) { require(_to != address(0)); require(_amount > 0); require(bytes(_data).length > 0); require(MAX_TOKEN_SUPPLY >= totalSupply_ + _amount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); // KYC frozens[_to] = true; FrozenAddress(_to); CreateTokenByAtes(_to, _amount, _data); Transfer(address(0), _to, _amount); return true; } }
authorizers[_addr] = false;
function delAuthorized(address _addr) external onlyAuthorized { require(_addr != address(0)); require(_addr != msg.sender); delete authorizers[_addr]; }
2,572,947
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; import "./comm/Ownable.sol"; import "./comm/SafeMath.sol"; import "./comm/IERC20.sol"; import "./comm/SafeERC20.sol"; import "./comm/ReentrancyGuard.sol"; interface IStrategy { function sharesTotal() external view returns(uint256); function wantTotal() external view returns(uint256); function getTotal() external view returns(uint256, uint256); function deposit(uint256 amount_) external returns(uint256); function withdraw(address user_, uint256 amount_, uint256 feeRate_) external returns(uint256); } interface IStrategyBNB { function deposit(uint256 amount_) external payable returns(uint256); } interface IVeMobox { function booster(address user_, uint256 totalShare_, uint256 wantShare_, address strategy_) external view returns(uint256); } interface IMoMoMinter { function addBox(address to_, uint256 amount_) external; } interface IKeyToken { function mint(address dest_, uint256 amount_) external; } contract MoboxFarm is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; event Staked(address indexed user, uint256 indexed pIndex, uint256 amount); event Withdrawn(address indexed user, uint256 indexed pIndex, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardRateChange(uint256 newRate); event AllocPointChange(uint256 indexed poolIndex, uint256 allocPoint, uint256 totalAllocPoint); struct UserInfo { uint128 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of KEYs // entitled to a user but is pending to be distributed is: // // pending reward = (user.workingBalance * pool.rewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `rewardPerShare` (and `lastRewardTime`) gets updated // 2. User receives the pending reward sent to his/her address // 3. User's `workingBalance` gets updated // 4. User's `rewardDebt` gets updated uint128 workingBalance; // Key, workingBalance = wantShares * mining bonus uint128 wantShares; // How many wantShares the user has get by LP Token provider. uint64 gracePeriod; // timestamp of that users can receive the staked LP/Token without deducting the transcation fee uint64 lastDepositBlock; // the blocknumber of the user's last deposit } struct PoolInfo { address wantToken; // Address of LP token/token contract uint32 allocPoint; // 1x = 100, 0.5x = 50 uint64 lastRewardTime; // Last unixtimestamp that CAKEs distribution occurs. uint128 rewardPerShare; // Accumulated KEYs per share, times 1e12. See below uint128 workingSupply; // Total mining points address strategy; // Strategy } address constant public BNB = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB; address public keyToken; address public momoMinter; // The contract for openning momo chests address public rewardMgr; // 'Key' mining rate management address public veMobox; // 'veCrv', mining weight address public rewardHelper; // If the user encounters a situation where there is not enough gas to receive the reward, the 'rewardHelper' can send the user's unclaimed 'Key' to the user uint256 public rewardRate; // rewardRate per second for minning uint256 public rewardStart; // reward start time uint256 public totalAllocPoint; // total allocPoint for all pools PoolInfo[] public poolInfoArray; mapping (uint256 => mapping (address => UserInfo)) _userInfoMap; mapping (address => uint256) public rewardStore; // Store rewards that the users did not withdraw function init(address key_, address rewardMgr_) external onlyOwner { require(keyToken == address(0) && rewardMgr == address(0), "only set once"); require(key_ != address(0) && rewardMgr_ != address(0), "invalid param"); keyToken = key_; rewardMgr = rewardMgr_; IERC20(keyToken).safeApprove(rewardMgr_, uint256(-1)); // Discard the first pool if (poolInfoArray.length == 0) { poolInfoArray.push(PoolInfo(address(0), 0, 0, 0, 0, address(0))); } emit RewardRateChange(0); } function setRewardHelper(address addr_) external onlyOwner { require(addr_ != address(0), "invalid param"); rewardHelper = addr_; } function setMoMoMinter(address addr_) external nonReentrant onlyOwner { require(keyToken != address(0) && addr_ != address(0), "invalid param"); if (momoMinter != address(0)) { require(IERC20(keyToken).approve(momoMinter, 0), "approve fail"); } momoMinter = addr_; // When the user exchanges the key for the box, 'momoMinter' will burn the specified number of keys. This method can be used to save gas, see 'getChestBox' IERC20(keyToken).safeApprove(momoMinter, uint256(-1)); } modifier onlyRewardMgr() { require(_msgSender() == rewardMgr, "not rewardMgr"); _; } // Add a new lp to the pool. Can only be called by the rewardMgr function addPool(address wantToken_, uint256 allocPoint_, address strategy_) external nonReentrant onlyRewardMgr { require(allocPoint_ <= 10000 && strategy_ != address(0), "invalid param"); // solium-disable-next-line if (block.timestamp > rewardStart) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.add(allocPoint_); uint256 poolIndex = poolInfoArray.length; poolInfoArray.push(PoolInfo({ wantToken: wantToken_, allocPoint: SafeMathExt.safe32(allocPoint_), lastRewardTime: uint64(block.timestamp), rewardPerShare: 0, workingSupply: 0, strategy: strategy_ })); if (wantToken_ != BNB) { IERC20(wantToken_).safeApprove(strategy_, uint256(-1)); } emit AllocPointChange(poolIndex, allocPoint_, totalAllocPoint); } function setPool(uint256 pIndex_, address wantToken_, uint256 allocPoint_) external nonReentrant onlyRewardMgr { PoolInfo storage pool = poolInfoArray[pIndex_]; // wantToken_ For verification only require(wantToken_ != address(0) && pool.wantToken == wantToken_, "invalid pool"); require(allocPoint_ >= 0 && allocPoint_ <= 10000, "invalid param"); massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(uint256(pool.allocPoint)).add(allocPoint_); pool.allocPoint = SafeMathExt.safe32(allocPoint_); emit AllocPointChange(pIndex_, allocPoint_, totalAllocPoint); } function getMaxPoolIndex() external view returns(uint256) { return poolInfoArray.length.sub(1); } function initReward(uint256 rewardRate_, uint256 rewardStart_) external onlyRewardMgr { require(rewardStart == 0, "only set once"); // solium-disable-next-line uint256 tmNow = block.timestamp; require(rewardRate_ > 0 && rewardRate_ <= 2e18 && rewardStart_ > tmNow, "invalid param"); rewardStart = rewardStart_; rewardRate = rewardRate_; emit RewardRateChange(rewardRate); } function changeRewardRate(uint256 rewardRate_) external onlyRewardMgr { require(rewardRate_ > 0 && rewardRate_ <= 2e18, "invalid param"); // solium-disable-next-line if (block.timestamp > rewardStart) { massUpdatePools(); } rewardRate = rewardRate_; emit RewardRateChange(rewardRate); } function setVeMobox(address veMobox_) external onlyRewardMgr { require(veMobox == address(0), "only set once"); veMobox = veMobox_; } function massUpdatePools() public { uint256 length = poolInfoArray.length; for (uint256 poolIndex = 0; poolIndex < length; ++poolIndex) { updatePool(poolIndex); } } function updatePool(uint256 pIndex_) public { PoolInfo storage pool = poolInfoArray[pIndex_]; // solium-disable-next-line uint256 blockTimeStamp = block.timestamp; if (pIndex_ <= 0 || blockTimeStamp <= rewardStart || blockTimeStamp <= pool.lastRewardTime) { return; } if (pool.workingSupply == 0) { pool.lastRewardTime = SafeMathExt.safe64(blockTimeStamp); return; } uint256 rewardTime = blockTimeStamp.sub(Math.max(uint256(pool.lastRewardTime), rewardStart)); uint256 keyReward = rewardTime.mul(rewardRate).mul(uint256(pool.allocPoint)).div(totalAllocPoint); IKeyToken(keyToken).mint(address(this), keyReward); pool.rewardPerShare = SafeMathExt.safe128( uint256(pool.rewardPerShare).add(keyReward.mul(1e12).div(uint256(pool.workingSupply))) ); pool.lastRewardTime = SafeMathExt.safe64(blockTimeStamp); } // View function to see pending KEYs on frontend. function pendingKey(uint256 pIndex_, address user_) external view returns(uint256) { // solium-disable-next-line uint256 blockTimeStamp = block.timestamp; if (pIndex_ <= 0 || blockTimeStamp <= rewardStart) { return 0; } PoolInfo storage pool = poolInfoArray[pIndex_]; if (blockTimeStamp < pool.lastRewardTime) { return 0; } UserInfo storage user = _userInfoMap[pIndex_][user_]; if (pool.workingSupply == 0 || user.workingBalance == 0) { return 0; } uint256 rewardPerShare = uint256(pool.rewardPerShare); uint256 rewardTime = blockTimeStamp.sub(Math.max(uint256(pool.lastRewardTime), rewardStart)); rewardPerShare = rewardPerShare.add( rewardTime.mul(rewardRate).mul(uint256(pool.allocPoint)).div(totalAllocPoint).mul(1e12).div(uint256(pool.workingSupply)) ); return uint256(user.workingBalance).mul(rewardPerShare).div(1e12).sub(user.rewardDebt); } function getUserInfo(uint256 pIndex_, address user_) external view returns( address wantToken, uint256 wantShares, uint256 wantAmount, uint256 workingBalance, uint256 gracePeriod ) { if (pIndex_ > 0) { PoolInfo storage pool = poolInfoArray[pIndex_]; UserInfo storage user = _userInfoMap[pIndex_][user_]; wantToken = pool.wantToken; wantShares = uint256(user.wantShares); workingBalance = uint256(user.workingBalance); gracePeriod = uint256(user.gracePeriod); uint256 wantTotal; uint256 shareTotal; (wantTotal, shareTotal) = IStrategy(pool.strategy).getTotal(); if (shareTotal > 0) { wantAmount = wantShares.mul(wantTotal).div(shareTotal); } else { wantAmount = 0; } } } function _boostWorkingBalance(address strategy_, address user_, uint256 sharesUser_) internal view returns(uint256) { if (veMobox == address(0)) { return 100; } uint256 sharesTotal = IStrategy(strategy_).sharesTotal(); return IVeMobox(veMobox).booster(user_, sharesTotal, sharesUser_, strategy_); } function _calcGracePeriod(uint256 gracePeriod, uint256 shareNew, uint256 shareAdd) internal view returns(uint256) { uint256 blockTime = block.timestamp; if (gracePeriod == 0) { // solium-disable-next-line return blockTime.add(180 days); } uint256 depositSec; // solium-disable-next-line if (blockTime >= gracePeriod) { depositSec = 180 days; return blockTime.add(depositSec.mul(shareAdd).div(shareNew)); } else { // solium-disable-next-line depositSec = uint256(180 days).sub(gracePeriod.sub(blockTime)); return gracePeriod.add(depositSec.mul(shareAdd).div(shareNew)); } } function _calcFeeRateByGracePeriod(uint256 gracePeriod) internal view returns(uint256) { // solium-disable-next-line if (block.timestamp >= gracePeriod) { return 0; } // solium-disable-next-line uint256 leftSec = gracePeriod.sub(block.timestamp); if (leftSec < 90 days) { return 10; // 0.1% } else if (leftSec < 150 days) { return 20; // 0.2% } else if (leftSec < 166 days) { return 30; // 0.3% } else if (leftSec < 173 days) { return 40; // 0.4% } else { return 50; // 0.5% } } function _depositFor(uint256 pIndex_, address lpFrom_, address lpFor_, uint256 amount_) internal { require(pIndex_ > 0 && amount_ > 0, "invalid param"); updatePool(pIndex_); PoolInfo storage pool = poolInfoArray[pIndex_]; UserInfo storage user = _userInfoMap[pIndex_][lpFor_]; if (pool.wantToken != BNB) { IERC20(pool.wantToken).safeTransferFrom(lpFrom_, address(this), amount_); } uint256 workingBalance = uint256(user.workingBalance); if (workingBalance > 0) { uint256 pending = workingBalance.mul(uint256(pool.rewardPerShare)).div(1e12).sub(uint256(user.rewardDebt)); if (pending > 0) { rewardStore[lpFor_] = pending.add(rewardStore[lpFor_]); } } // The return value of 'deposit' is the latest 'share' value uint256 wantSharesOld = uint256(user.wantShares); uint256 shareAdd; if (pool.wantToken == BNB) { shareAdd = IStrategyBNB(pool.strategy).deposit{value: amount_}(amount_); } else { shareAdd = IStrategy(pool.strategy).deposit(amount_); } user.wantShares = SafeMathExt.safe128(wantSharesOld.add(shareAdd)); uint256 boost = _boostWorkingBalance(pool.strategy, lpFor_, uint256(user.wantShares)); require(boost >= 100 && boost <= 300, "invalid boost"); uint256 oldWorkingBalance = uint256(user.workingBalance); uint256 newWorkingBalance = uint256(user.wantShares).mul(boost).div(100); user.workingBalance = SafeMathExt.safe128(newWorkingBalance); pool.workingSupply = SafeMathExt.safe128(uint256(pool.workingSupply).sub(oldWorkingBalance).add(newWorkingBalance)); user.rewardDebt = SafeMathExt.safe128(newWorkingBalance.mul(uint256(pool.rewardPerShare)).div(1e12)); user.gracePeriod = SafeMathExt.safe64(_calcGracePeriod(user.gracePeriod, uint256(user.wantShares), shareAdd)); user.lastDepositBlock = SafeMathExt.safe64(block.number); emit Staked(lpFor_, pIndex_, amount_); } // Deposit LP tokens/BEP20 tokens to MOBOXFarm for KEY allocation. function deposit(uint256 pIndex_, uint256 amount_) external nonReentrant { _depositFor(pIndex_, msg.sender, msg.sender, amount_); } // Deposit BNB to MOBOXFarm for KEY allocation. function deposit(uint256 pIndex_) external payable nonReentrant { _depositFor(pIndex_, msg.sender, msg.sender, msg.value); } // Deposit LP tokens/BEP20 tokens to MOBOXFarm for KEY allocation. function depositFor(address lpFor_, uint256 pIndex_, uint256 amount_) external nonReentrant { _depositFor(pIndex_, msg.sender, lpFor_, amount_); } // Deposit BNB to MOBOXFarm for KEY allocation. function depositFor(address lpFor_, uint256 pIndex_) external payable nonReentrant { _depositFor(pIndex_, msg.sender, lpFor_, msg.value); } // Stake CAKE tokens to MoboxFarm function withdraw(uint256 pIndex_, uint256 amount_) external nonReentrant { require(pIndex_ > 0 || amount_ > 0, "invalid param"); updatePool(pIndex_); PoolInfo storage pool = poolInfoArray[pIndex_]; UserInfo storage user = _userInfoMap[pIndex_][msg.sender]; uint256 wantShares = uint256(user.wantShares); require(wantShares > 0, "insufficient wantShares"); require(block.number > uint256(user.lastDepositBlock).add(2), "withdraw in 3 blocks"); uint256[2] memory shareTotals; // 0: wantTotal, 1: shareTotal (shareTotals[0], shareTotals[1]) = IStrategy(pool.strategy).getTotal(); require(shareTotals[1] >= wantShares, "invalid share"); uint256 pending = uint256(user.workingBalance).mul(uint256(pool.rewardPerShare)).div(1e12).sub(uint256(user.rewardDebt)); uint256 wantWithdraw = wantShares.mul(shareTotals[0]).div(shareTotals[1]); if (wantWithdraw > amount_) { wantWithdraw = amount_; } require(wantWithdraw > 0, "insufficient wantAmount"); uint256 feeRate = _calcFeeRateByGracePeriod(uint256(user.gracePeriod)); uint256 shareSub = IStrategy(pool.strategy).withdraw(msg.sender, wantWithdraw, feeRate); user.wantShares = SafeMathExt.safe128(uint256(user.wantShares).sub(shareSub)); uint256 boost = _boostWorkingBalance(pool.strategy, msg.sender, uint256(user.wantShares)); require(boost >= 100 && boost <= 300, "invalid boost"); uint256 oldWorkingBalance = uint256(user.workingBalance); uint256 newWorkingBalance = uint256(user.wantShares).mul(boost).div(100); user.workingBalance = SafeMathExt.safe128(newWorkingBalance); // Set 'rewardDebt' first and then increase 'rewardStore' user.rewardDebt = SafeMathExt.safe128(newWorkingBalance.mul(uint256(pool.rewardPerShare)).div(1e12)); if (pending > 0) { rewardStore[msg.sender] = pending.add(rewardStore[msg.sender]); } // If user withdraws all the LPs, then gracePeriod is cleared if (user.wantShares == 0) { user.gracePeriod = 0; } pool.workingSupply = SafeMathExt.safe128(uint256(pool.workingSupply).sub(oldWorkingBalance).add(newWorkingBalance)); emit Staked(msg.sender, pIndex_, amount_); } function getReward(uint256[] memory pIndexArray_) external nonReentrant { _getRward(pIndexArray_, msg.sender); uint256 keyAmount = rewardStore[msg.sender]; if (keyAmount > 0) { rewardStore[msg.sender] = 0; IERC20(keyToken).safeTransfer(msg.sender, keyAmount); emit RewardPaid(msg.sender, keyAmount); } } function updateRewardByVeMobox(uint256 poolIndex_, address user_) external { require(msg.sender == veMobox, "invalid caller"); require(poolIndex_ > 0 && poolIndex_ < poolInfoArray.length, "invalid param"); uint256[] memory pIndexArray = new uint256[](1); pIndexArray[0] = poolIndex_; _getRward(pIndexArray, user_); } function getRewardFor(uint256[] memory pIndexArray_, address user_) external { require(msg.sender == rewardHelper, "not helper"); _getRward(pIndexArray_, user_); uint256 keyAmount = rewardStore[user_]; if (keyAmount > 0) { rewardStore[user_] = 0; IERC20(keyToken).safeTransfer(user_, keyAmount); emit RewardPaid(user_, keyAmount); } } function _getRward(uint256[] memory pIndexArray_, address user_) internal { require(pIndexArray_.length > 0 && user_ != address(0), "invalid param"); uint256 poolIndex; uint256 keyAmount = rewardStore[user_]; for (uint256 i = 0; i < pIndexArray_.length; ++i) { poolIndex = pIndexArray_[i]; UserInfo storage user = _userInfoMap[poolIndex][user_]; if (user.workingBalance <= 0) { continue; } updatePool(poolIndex); PoolInfo storage pool = poolInfoArray[poolIndex]; uint256 workingBalance = uint256(user.workingBalance); uint256 pending = workingBalance.mul(uint256(pool.rewardPerShare)).div(1e12).sub(uint256(user.rewardDebt)); // Need to check the change of boost rate if (veMobox != address(0)) { uint256 boost = _boostWorkingBalance(pool.strategy, user_, uint256(user.wantShares)); require(boost >= 100 && boost <= 300, "invalid boost"); uint256 oldWorkingBalance = workingBalance; uint256 newWorkingBalance = uint256(user.wantShares).mul(boost).div(100); if (oldWorkingBalance != newWorkingBalance) { user.workingBalance = SafeMathExt.safe128(newWorkingBalance); pool.workingSupply = SafeMathExt.safe128(uint256(pool.workingSupply).sub(oldWorkingBalance).add(newWorkingBalance)); workingBalance = newWorkingBalance; } } user.rewardDebt = SafeMathExt.safe128(workingBalance.mul(uint256(pool.rewardPerShare)).div(1e12)); keyAmount = keyAmount.add(pending); } rewardStore[user_] = keyAmount; } function getChestBox(uint256[] memory pIndexArray_, uint256 boxAmount_) external nonReentrant { require(boxAmount_ > 0 && boxAmount_ < 10000000 && momoMinter != address(0), "invalid param"); if (rewardStore[msg.sender] < boxAmount_.mul(1e18)) { _getRward(pIndexArray_, msg.sender); } uint256 keyAmount = rewardStore[msg.sender]; uint256 needKey = boxAmount_.mul(1e18); if (keyAmount >= needKey) { rewardStore[msg.sender] = keyAmount.sub(needKey); IMoMoMinter(momoMinter).addBox(msg.sender, boxAmount_); emit RewardPaid(msg.sender, needKey); } } }
Add a new lp to the pool. Can only be called by the rewardMgr solium-disable-next-line
function addPool(address wantToken_, uint256 allocPoint_, address strategy_) external nonReentrant onlyRewardMgr { require(allocPoint_ <= 10000 && strategy_ != address(0), "invalid param"); if (block.timestamp > rewardStart) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.add(allocPoint_); uint256 poolIndex = poolInfoArray.length; poolInfoArray.push(PoolInfo({ wantToken: wantToken_, allocPoint: SafeMathExt.safe32(allocPoint_), lastRewardTime: uint64(block.timestamp), rewardPerShare: 0, workingSupply: 0, strategy: strategy_ })); if (wantToken_ != BNB) { IERC20(wantToken_).safeApprove(strategy_, uint256(-1)); } emit AllocPointChange(poolIndex, allocPoint_, totalAllocPoint); }
5,348,547
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./MMR.sol"; import "./tokenbridge/arbitrum/StandardArbERC20.sol"; import "./buddybridge/ethereum/L1Buddy.sol"; import "arbos-contracts/arbos/builtin/ArbSys.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract ArbBatchTokenMover { using MMR for MMR.Tree; MMR.Tree withdrawalTree; uint256 exitBlock; StandardArbERC20 erc20; function withdrawInBatch(uint256 amount) external { require(erc20.transferFrom(msg.sender, address(this), amount), "TRANSFER_FAILED"); withdrawalTree.append(abi.encode(msg.sender, amount)); } function exitToL1() external { require(block.number >= exitBlock, "TOO_SOON"); ArbSys(100).sendTxToL1( address(this), abi.encodeWithSignature( "distributeBatch(bytes32,address)", withdrawalTree.getRoot(), erc20.l1Address() ) ); erc20.withdraw(address(this), erc20.balanceOf(address(this))); selfdestruct(msg.sender); } } contract EthBatchTokenReceiver is L1Buddy { bytes32 root; IERC20 erc20; mapping(uint256 => bool) redeemed; constructor( address _inbox, address _l2Deployer, uint256 _maxSubmissionCost, uint256 _maxGas, uint256 _gasPrice ) public payable L1Buddy(_inbox, _l2Deployer) { L1Buddy.initiateBuddyDeploy( _maxSubmissionCost, _maxGas, _gasPrice, type(ArbBatchTokenMover).creationCode ); } function handleDeploySuccess() internal override { // this deletes the codehash from state! L1Buddy.handleDeploySuccess(); } function handleDeployFail() internal override {} function distributeBatch(bytes32 _root) external onlyIfConnected onlyL2Buddy { root = _root; } function redeemWithdrawal( address dest, uint256 amount, uint256 width, uint256 index, bytes32[] memory peaks, bytes32[] memory siblings ) public { require(root != 0, "NOT_INITIALIZED"); require(!redeemed[index], "ALREADY_REDEEMED"); redeemed[index] = true; require( MMR.inclusionProof(root, width, index, abi.encode(dest, amount), peaks, siblings) == true, "BAD_PROOF" ); require(erc20.transfer(dest, amount), "BAD_TRANSFER"); } }
this deletes the codehash from state!
function handleDeploySuccess() internal override { L1Buddy.handleDeploySuccess(); }
5,425,806
./full_match/56/0xc4206342394Acec895913Fcf11cd44dbEfF94c6c/sources/project_/contracts/Ticket.sol
Set `_newFactory` as `_factory` The caller must be TicketAdmin.
function setFactory(address _newFactory) external onlyTicketAdmin { _factory = _newFactory; }
3,258,416
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; pragma abicoder v2; import "../utils/GsnTypes.sol"; /** * @title The RelayHub Validator Library * @notice Validates the `msg.data` received by the `RelayHub` does not contain unnecessary bytes. * Including these extra bytes would allow the Relay Server to inflate transaction costs and overcharge the client. */ library RelayHubValidator { /// @notice Validate that encoded `relayCall` is properly packed without any extra bytes function verifyTransactionPacking( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData ) internal pure { // abicoder v2: https://docs.soliditylang.org/en/latest/abi-spec.html // each static param/member is 1 word // struct (with dynamic members) has offset to struct which is 1 word // dynamic member is 1 word offset to actual value, which is 1-word length and ceil(length/32) words for data // relayCall has 5 method params, // relayRequest: 2 members // relayData 9 members // ForwardRequest: 7 members // total 22 32-byte words if all dynamic params are zero-length. uint256 expectedMsgDataLen = 4 + 23 * 32 + dynamicParamSize(signature) + dynamicParamSize(approvalData) + dynamicParamSize(relayRequest.request.data) + dynamicParamSize(relayRequest.relayData.paymasterData); // zero-length signature is allowed in a batch relay transaction require(signature.length <= 65, "invalid signature length"); require(expectedMsgDataLen == msg.data.length, "extra msg.data bytes" ); } // helper method for verifyTransactionPacking: // size (in bytes) of the given "bytes" parameter. size include the length (32-byte word), // and actual data size, rounded up to full 32-byte words function dynamicParamSize(bytes calldata buf) internal pure returns (uint256) { return 32 + ((buf.length + 31) & (type(uint256).max - 31)); } }
helper method for verifyTransactionPacking: size (in bytes) of the given "bytes" parameter. size include the length (32-byte word), and actual data size, rounded up to full 32-byte words
function dynamicParamSize(bytes calldata buf) internal pure returns (uint256) { return 32 + ((buf.length + 31) & (type(uint256).max - 31)); }
5,476,262
./full_match/11155111/0x945217B1bA47Ad0834e838ae173FB8B4B9135314/sources/src/NFTDriver.sol
Registers the next token ID when minting. return tokenId The registered token ID.
function _registerTokenId() internal returns (uint256 tokenId) { tokenId = nextTokenId(); _nftDriverStorage().mintedTokens++; }
3,820,059
./full_match/83/0x48ef19252C6c59c5CF1e5Bd87DAeE0A2c5BA7cEE/sources/contracts/CToken/CToken.sol
Accepts transfer of admin rights. msg.sender must be pendingAdmin Admin function for pending admin to accept role and update admin return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller is pendingAdmin and pendingAdmin ≠ address(0)
function _acceptAdmin() external override returns (uint256) { if (msg.sender != pendingAdmin || msg.sender == address(0)) { return Error.UNAUTHORIZED.fail(FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } address oldPendingAdmin = pendingAdmin; emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); }
9,556,721
// SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '../interfaces/IElasticToken.sol'; import '../libraries/ElasticMath.sol'; import '../core/ElasticDAO.sol'; import '../models/DAO.sol'; import '../models/Ecosystem.sol'; import '../models/Token.sol'; import '../models/TokenHolder.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; /** * @dev ElasticGovernanceToken contract outlines and defines all the functionality * of an ElasticGovernanceToken and also serves as it's storage */ contract ElasticGovernanceToken is IElasticToken, ReentrancyGuard { address public burner; address public daoAddress; address public ecosystemModelAddress; address public minter; bool public initialized; mapping(address => mapping(address => uint256)) private _allowances; modifier onlyDAO() { require(msg.sender == daoAddress, 'ElasticDAO: Not authorized'); _; } modifier onlyDAOorBurner() { require(msg.sender == daoAddress || msg.sender == burner, 'ElasticDAO: Not authorized'); _; } modifier onlyDAOorMinter() { require(msg.sender == daoAddress || msg.sender == minter, 'ElasticDAO: Not authorized'); _; } /** * @notice initializes the ElasticGovernanceToken * * @param _burner - the address which can burn tokens * @param _minter - the address which can mint tokens * @param _ecosystem - Ecosystem Instance * @param _token - Token Instance * * @dev Requirements: * - The token should not already be initialized * - The address of the burner cannot be zero * - The address of the deployed ElasticDAO cannot be zero * - The address of the ecosystemModelAddress cannot be zero * - The address of the minter cannot be zero * * @return bool */ function initialize( address _burner, address _minter, Ecosystem.Instance memory _ecosystem, Token.Instance memory _token ) external nonReentrant returns (Token.Instance memory) { require(initialized == false, 'ElasticDAO: Already initialized'); require(_burner != address(0), 'ElasticDAO: Address Zero'); require(_ecosystem.daoAddress != address(0), 'ElasticDAO: Address Zero'); require(_ecosystem.ecosystemModelAddress != address(0), 'ElasticDAO: Address Zero'); require(_minter != address(0), 'ElasticDAO: Address Zero'); initialized = true; burner = _burner; daoAddress = _ecosystem.daoAddress; ecosystemModelAddress = _ecosystem.ecosystemModelAddress; minter = _minter; Token tokenStorage = Token(_ecosystem.tokenModelAddress); tokenStorage.serialize(_token); return _token; } /** * @notice Returns the remaining number of tokens that @param _spender will be * allowed to spend on behalf of @param _owner through {transferFrom}. This is * zero by default * * @param _spender - the address of the spender * @param _owner - the address of the owner * * @dev This value changes when {approve} or {transferFrom} are called * * @return uint256 */ function allowance(address _owner, address _spender) external view override returns (uint256) { return _allowances[_owner][_spender]; } /** * @notice Sets @param _amount as the allowance of @param _spender over the caller's tokens * * @param _spender - the address of the spender * * @dev * 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 * * @dev Emits an {Approval} event * * @return bool */ function approve(address _spender, uint256 _amount) external override nonReentrant returns (bool) { _approve(msg.sender, _spender, _amount); return true; } /** * @notice Returns the amount of tokens owned by @param _account using ElasticMath * * @param _account - address of the account * * @dev the number of tokens is given by: * t = lambda * m * k * * t - number of tokens * m - lambda modifier - it's value increases every time someone joins the DAO * k - constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return uint256 */ function balanceOf(address _account) external view override returns (uint256) { Token.Instance memory token = _getToken(); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); uint256 t = ElasticMath.t(tokenHolder.lambda, token.k, token.m); return t; } /** * @notice Returns the amount of shares ( lambda ) owned by _account. * * @param _account - address of the account * * @return lambda uint256 - lambda is the number of shares */ function balanceOfInShares(address _account) external view override returns (uint256) { TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); return tokenHolder.lambda; } /** * @notice Returns the amount of tokens @param _account can vote with, using ElasticMath * * @param _account - the address of the account * * @dev checks if @param _account has more or less lambda than maxVotingLambda, * based on which number of tokens (t) @param _account can vote with is calculated. * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return balance uint256 numberOfTokens (t) */ function balanceOfVoting(address _account) external view returns (uint256 balance) { Token.Instance memory token = _getToken(); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); uint256 maxVotingLambda = _getDAO().maxVotingLambda; if (tokenHolder.lambda > maxVotingLambda) { return ElasticMath.t(maxVotingLambda, token.k, token.m); } else { return ElasticMath.t(tokenHolder.lambda, token.k, token.m); } } /** * @notice Reduces the balance(tokens) of @param _account by _amount * * @param _account address of the account * * @param _amount - the amount by which the number of tokens is to be reduced * * @return bool */ function burn(address _account, uint256 _amount) external override onlyDAOorBurner nonReentrant returns (bool) { _burn(_account, _amount); return true; } /** * @notice Reduces the balance(lambda) of @param _account by _amount * * @param _account - address of the account * * @param _amount - the amount by which the number of shares has to be reduced * * @return bool */ function burnShares(address _account, uint256 _amount) external override onlyDAOorBurner nonReentrant returns (bool) { _burnShares(_account, _amount); return true; } /** * @notice returns the number of decimals * * @return 18 */ function decimals() external pure returns (uint256) { return 18; } /** * @notice decreases the allowance of @param _spender by _subtractedValue * * @param _spender - address of the spender * @param _subtractedValue - the value the allowance has to be decreased by * * @dev Requirement: * Allowance cannot be lower than 0 * * @return bool */ function decreaseAllowance(address _spender, uint256 _subtractedValue) external nonReentrant returns (bool) { uint256 newAllowance = SafeMath.sub(_allowances[msg.sender][_spender], _subtractedValue); _approve(msg.sender, _spender, newAllowance); return true; } /** * @notice increases the allowance of @param _spender by _addedValue * * @param _spender - address of the spender * @param _addedValue - the value the allowance has to be increased by * * @return bool */ function increaseAllowance(address _spender, uint256 _addedValue) external nonReentrant returns (bool) { _approve(msg.sender, _spender, SafeMath.add(_allowances[msg.sender][_spender], _addedValue)); return true; } /** * @dev mints @param _amount tokens for @param _account * @param _account - the address of the account for whom the token have to be minted to * @param _amount - the amount of tokens to be minted * @return bool */ function mint(address _account, uint256 _amount) external override onlyDAOorMinter nonReentrant returns (bool) { _mint(_account, _amount); return true; } /** * @dev mints @param _amount of shares for @param _account * @param _account address of the account * @param _amount - the amount of shares to be minted * @return bool */ function mintShares(address _account, uint256 _amount) external override onlyDAOorMinter nonReentrant returns (bool) { _mintShares(_account, _amount); return true; } /** * @dev Returns the name of the token. * @return string - name of the token */ function name() external view returns (string memory) { return _getToken().name; } /** * @notice Returns the number of token holders of ElasticGovernanceToken * * @return uint256 numberOfTokenHolders */ function numberOfTokenHolders() external view override returns (uint256) { return _getToken().numberOfTokenHolders; } /** * @notice sets the burner of the ElasticGovernanceToken * a Burner is an address that can burn tokens(reduce the amount of tokens in circulation) * * @param _burner - the address of the burner * * @dev Requirement: * - Address of the burner cannot be zero address * * @return bool */ function setBurner(address _burner) external onlyDAO nonReentrant returns (bool) { require(_burner != address(0), 'ElasticDAO: Address Zero'); burner = _burner; return true; } /** * @notice sets the minter of the ElasticGovernanceToken * a Minter is an address that can mint tokens(increase the amount of tokens in circulation) * * @param _minter - address of the minter * * @dev Requirement: * - Address of the minter cannot be zero address * * @return bool */ function setMinter(address _minter) external onlyDAO nonReentrant returns (bool) { require(_minter != address(0), 'ElasticDAO: Address Zero'); minter = _minter; return true; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. * * @return string - the symbol of the token */ function symbol() external view returns (string memory) { return _getToken().symbol; } /** * @notice returns the totalSupply of tokens in the DAO * * @dev * t - the total number of tokens in the DAO * lambda - the total number of shares outstanding in the DAO currently * m - current value of the share modifier * k - constant * t = ( lambda * m * k ) * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return uint256 - the value of t */ function totalSupply() external view override returns (uint256) { Token.Instance memory token = _getToken(); return ElasticMath.t(token.lambda, token.k, token.m); } /** * @notice Returns the current lambda value * * @return uint256 lambda */ function totalSupplyInShares() external view override returns (uint256) { Token.Instance memory token = _getToken(); return token.lambda; } /** * @dev Moves @param _amount tokens from the caller's account to @param _to address * * Returns a boolean value indicating whether the operation succeeded * * Emits a {Transfer} event * @return bool */ function transfer(address _to, uint256 _amount) external override nonReentrant returns (bool) { _transfer(msg.sender, _to, _amount); return true; } /** * @dev Moves @param _amount tokens from @param _from to @param _to using the * allowance mechanism. @param _amount is then deducted from the caller's * allowance * * Returns a boolean value indicating whether the operation succeeded * * Emits a {Transfer} event * @return bool */ function transferFrom( address _from, address _to, uint256 _amount ) external override nonReentrant returns (bool) { require(msg.sender == _from || _amount <= _allowances[_from][msg.sender], 'ERC20: Bad Caller'); if (msg.sender != _from && _allowances[_from][msg.sender] != uint256(-1)) { _allowances[_from][msg.sender] = SafeMath.sub(_allowances[_from][msg.sender], _amount); emit Approval(_from, msg.sender, _allowances[_from][msg.sender]); } _transfer(_from, _to, _amount); return true; } // Private 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); } function _burn(address _account, uint256 _deltaT) internal { Token.Instance memory token = _getToken(); uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); _burnShares(_account, deltaLambda); } function _burnShares(address _account, uint256 _deltaLambda) internal { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); bool alreadyTokenHolder = tokenHolder.lambda > 0; uint256 deltaT = ElasticMath.t(_deltaLambda, token.k, token.m); tokenHolder = _updateBalance(tokenHolder, false, _deltaLambda); token.lambda = SafeMath.sub(token.lambda, _deltaLambda); tokenStorage.serialize(token); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(tokenHolder); _updateNumberOfTokenHolders(alreadyTokenHolder, token, tokenHolder, tokenStorage); emit Transfer(_account, address(0), deltaT); } function _mint(address _account, uint256 _deltaT) internal { Token.Instance memory token = _getToken(); uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); _mintShares(_account, deltaLambda); } function _mintShares(address _account, uint256 _deltaLambda) internal { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); bool alreadyTokenHolder = tokenHolder.lambda > 0; uint256 deltaT = ElasticMath.t(_deltaLambda, token.k, token.m); tokenHolder = _updateBalance(tokenHolder, true, _deltaLambda); token.lambda = SafeMath.add(token.lambda, _deltaLambda); tokenStorage.serialize(token); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(tokenHolder); _updateNumberOfTokenHolders(alreadyTokenHolder, token, tokenHolder, tokenStorage); emit Transfer(address(0), _account, deltaT); } function _transfer( address _from, address _to, uint256 _deltaT ) internal { require(_from != _to, 'ElasticDAO: Can not transfer to self'); Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory fromTokenHolder = _getTokenHolder(_from); TokenHolder.Instance memory toTokenHolder = _getTokenHolder(_to); bool fromAlreadyTokenHolder = fromTokenHolder.lambda > 0; bool toAlreadyTokenHolder = toTokenHolder.lambda > 0; uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); uint256 deltaT = ElasticMath.t(deltaLambda, token.k, token.m); fromTokenHolder = _updateBalance(fromTokenHolder, false, deltaLambda); toTokenHolder = _updateBalance(toTokenHolder, true, deltaLambda); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(fromTokenHolder); tokenHolderStorage.serialize(toTokenHolder); _updateNumberOfTokenHolders(fromAlreadyTokenHolder, token, fromTokenHolder, tokenStorage); _updateNumberOfTokenHolders(toAlreadyTokenHolder, token, toTokenHolder, tokenStorage); emit Transfer(_from, _to, deltaT); } function _updateBalance( TokenHolder.Instance memory _tokenHolder, bool _isIncreasing, uint256 _deltaLambda ) internal pure returns (TokenHolder.Instance memory) { if (_isIncreasing) { _tokenHolder.lambda = SafeMath.add(_tokenHolder.lambda, _deltaLambda); } else { _tokenHolder.lambda = SafeMath.sub(_tokenHolder.lambda, _deltaLambda); } return _tokenHolder; } function _updateNumberOfTokenHolders( bool alreadyTokenHolder, Token.Instance memory token, TokenHolder.Instance memory tokenHolder, Token tokenStorage ) internal { if (tokenHolder.lambda > 0 && alreadyTokenHolder == false) { tokenStorage.updateNumberOfTokenHolders(token, SafeMath.add(token.numberOfTokenHolders, 1)); } if (tokenHolder.lambda == 0 && alreadyTokenHolder) { tokenStorage.updateNumberOfTokenHolders(token, SafeMath.sub(token.numberOfTokenHolders, 1)); } } // Private Getters function _getDAO() internal view returns (DAO.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return DAO(ecosystem.daoModelAddress).deserialize(daoAddress, ecosystem); } function _getEcosystem() internal view returns (Ecosystem.Instance memory) { return Ecosystem(ecosystemModelAddress).deserialize(daoAddress); } function _getTokenHolder(address _account) internal view returns (TokenHolder.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return TokenHolder(ecosystem.tokenHolderModelAddress).deserialize( _account, ecosystem, Token(ecosystem.tokenModelAddress).deserialize(address(this), ecosystem) ); } function _getToken() internal view returns (Token.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return Token(ecosystem.tokenModelAddress).deserialize(address(this), ecosystem); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IElasticToken is IERC20 { /** * @dev Returns the amount of shares owned by @param _account. * @param _account - address of the account * @return lambda uint256 - lambda is the number of shares */ function balanceOfInShares(address _account) external view returns (uint256 lambda); /** * @dev Reduces the balance(tokens) of @param _account by @param _amount * @param _account address of the account * @param _amount - the amount by which the number of tokens has to be reduced * @return bool */ function burn(address _account, uint256 _amount) external returns (bool); /** * @dev Reduces the balance(shares) of @param _account by @param _amount * @param _account - address of the account * @param _amount - the amount by which the number of shares has to be reduced * @return bool */ function burnShares(address _account, uint256 _amount) external returns (bool); /** * @dev mints @param _amount tokens for @param _account * @param _account - the address of the account for whom the token have to be minted to * @param _amount - the amount of tokens to be minted * @return bool */ function mint(address _account, uint256 _amount) external returns (bool); /** * @dev mints @param _amount of shares for @param _account * @param _account address of the account * @param _amount - the amount of shares to be minted * @return bool */ function mintShares(address _account, uint256 _amount) external returns (bool); /** * @dev returns total number of token holders * @return uint256 */ function numberOfTokenHolders() external view returns (uint256); /** * @dev Returns the total supply of shares in the DAO * @return lambda uint256 - lambda is the number of shares */ function totalSupplyInShares() external view returns (uint256 lambda); } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; import './SafeMath.sol'; /** * @dev Provides functions for performing ElasticDAO specific math. * * These functions correspond with functions provided by the JS SDK and should * always be used instead of doing calculations within other contracts to avoid * any inconsistencies in the math. * * Notes: * * - Dash values represent the state after a transaction has completed successfully. * - Non-dash values represent the current state, before the transaction has completed. * - Lambda is the math term for shares. We typically expose the value to users as * shares instead of lambda because it's easier to grok. */ library ElasticMath { /** * @dev calculates the value of capitalDelta; the amount of ETH backing each * governance token. * @param totalEthValue amount of ETH in the DAO contract * @param totalSupplyOfTokens number of tokens in existance * * capitalDelta = totalEthValue / totalSupplyOfTokens * @return uint256 */ function capitalDelta(uint256 totalEthValue, uint256 totalSupplyOfTokens) internal pure returns (uint256) { return wdiv(totalEthValue, totalSupplyOfTokens); } /** * @dev calculates the value of deltaE; the amount of ETH required to mint deltaLambda * @param deltaLambda = lambdaDash - lambda * @param capitalDeltaValue the ETH/token ratio; see capitalDelta(uint256, uint256) * @param k constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * @param elasticity the percentage by which capitalDelta (cost of entering the DAO) * should increase on every join * @param lambda outstanding shares * @param m - lambda modifier - it's value increases every time someone joins the DAO * * lambdaDash = deltaLambda + lambda * mDash = ( lambdaDash / lambda ) * m * deltaE = capitalDelta * k * ( lambdaDash * mDash * ( 1 + elasticity ) - lambda * m ) * @return uint256 */ function deltaE( uint256 deltaLambda, uint256 capitalDeltaValue, uint256 k, uint256 elasticity, uint256 lambda, uint256 m ) internal pure returns (uint256) { uint256 lambdaDash = SafeMath.add(deltaLambda, lambda); return wmul( wmul(capitalDeltaValue, k), SafeMath.sub( wmul(lambdaDash, wmul(mDash(lambdaDash, lambda, m), revamp(elasticity))), wmul(lambda, m) ) ); } /** * @dev calculates the lambda value given t, k, & m * @param tokens t value; number of tokens for which lambda should be calculated * @param k constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * @param m - lambda modifier - it's value increases every time someone joins the DAO * * lambda = t / ( m * k) * @return uint256 */ function lambdaFromT( uint256 tokens, uint256 k, uint256 m ) internal pure returns (uint256) { return wdiv(tokens, wmul(k, m)); } /** * @dev calculates the future share modifier given the future value of * lambda (lambdaDash), the current value of lambda, and the current share modifier * @param m current share modifier * @param lambda current outstanding shares * @param lambdaDash future outstanding shares * * mDash = ( lambdaDash / lambda ) * m * @return uint256 */ function mDash( uint256 lambdaDash, uint256 lambda, uint256 m ) internal pure returns (uint256) { return wmul(wdiv(lambdaDash, lambda), m); } /** * @dev calculates the value of revamp * @param elasticity the percentage by which capitalDelta should increase * * revamp = 1 + elasticity * @return uint256 */ function revamp(uint256 elasticity) internal pure returns (uint256) { return SafeMath.add(elasticity, 1000000000000000000); } /** * @dev calculates the number of tokens represented by lambda given k & m * @param lambda shares * @param k a constant, initially set by the DAO * @param m share modifier * * t = lambda * m * k * @return uint256 */ function t( uint256 lambda, uint256 k, uint256 m ) internal view returns (uint256) { if (lambda == 0) { return 0; } return wmul(wmul(lambda, k), m); } /** * @dev multiplies two float values, required since solidity does not handle * floating point values * * inspiration: https://github.com/dapphub/ds-math/blob/master/src/math.sol * * @return uint256 */ function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return SafeMath.div( SafeMath.add(SafeMath.mul(a, b), SafeMath.div(1000000000000000000, 2)), 1000000000000000000 ); } /** * @dev divides two float values, required since solidity does not handle * floating point values. * * inspiration: https://github.com/dapphub/ds-math/blob/master/src/math.sol * * @return uint256 */ function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return SafeMath.div(SafeMath.add(SafeMath.mul(a, 1000000000000000000), SafeMath.div(b, 2)), b); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '../interfaces/IUniswapV2Pair.sol'; import '../libraries/ElasticMath.sol'; import '../models/DAO.sol'; import '../models/Ecosystem.sol'; import '../models/Token.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import '@pie-dao/proxy/contracts/PProxy.sol'; import 'hardhat/console.sol'; /** * @dev The ElasticDAO contract outlines and defines all the functionality * such as initialize, Join, exit, etc for an elasticDAO. * * It also serves as the vault for ElasticDAO. */ contract ElasticDAO is ReentrancyGuard { address public deployer; address public ecosystemModelAddress; address public controller; address[] public summoners; address[] public liquidityPools; bool public initialized; event ElasticGovernanceTokenDeployed(address indexed tokenAddress); event MaxVotingLambdaChanged(uint256 value); event ControllerChanged(address value); event ExitDAO(address indexed memberAddress, uint256 shareAmount, uint256 ethAmount); event FailedToFullyPenalize( address indexed memberAddress, uint256 attemptedAmount, uint256 actualAmount ); event JoinDAO(address indexed memberAddress, uint256 shareAmount, uint256 ethAmount); event LiquidityPoolAdded(address indexed poolAddress); event LiquidityPoolRemoved(address indexed poolAddress); event SeedDAO(address indexed summonerAddress, uint256 amount); event SummonedDAO(address indexed summonedBy); modifier onlyAfterSummoning() { DAO.Instance memory dao = _getDAO(); require(dao.summoned, 'ElasticDAO: DAO must be summoned'); _; } modifier onlyAfterTokenInitialized() { Ecosystem.Instance memory ecosystem = _getEcosystem(); bool tokenInitialized = Token(ecosystem.tokenModelAddress).exists( ecosystem.governanceTokenAddress, ecosystem.daoAddress ); require(tokenInitialized, 'ElasticDAO: Please call initializeToken first'); _; } modifier onlyBeforeSummoning() { DAO.Instance memory dao = _getDAO(); require(dao.summoned == false, 'ElasticDAO: DAO must not be summoned'); _; } modifier onlyController() { require(msg.sender == controller, 'ElasticDAO: Only controller'); _; } modifier onlyDeployer() { require(msg.sender == deployer, 'ElasticDAO: Only deployer'); _; } modifier onlySummoners() { Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoContract = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoContract.deserialize(address(this), ecosystem); bool summonerCheck = daoContract.isSummoner(dao, msg.sender); require(summonerCheck, 'ElasticDAO: Only summoners'); _; } modifier onlyWhenOpen() { require(address(this).balance > 0, 'ElasticDAO: This DAO is closed'); _; } /** * @notice Initializes and builds the ElasticDAO struct * * @param _ecosystemModelAddress - the address of the ecosystem model * @param _controller the address which can control the core DAO functions * @param _summoners - an array containing the addresses of the summoners * @param _name - the name of the DAO * @param _maxVotingLambda - the maximum amount of lambda that can be used to vote in the DAO * * @dev * Requirements: * - The DAO cannot already be initialized * - The ecosystem model address cannot be the zero address * - The DAO must have atleast one summoner to summon the DAO */ function initialize( address _ecosystemModelAddress, address _controller, address[] memory _summoners, string memory _name, uint256 _maxVotingLambda ) external nonReentrant { require(initialized == false, 'ElasticDAO: Already initialized'); require( _ecosystemModelAddress != address(0) && _controller != address(0), 'ElasticDAO: Address Zero' ); require(_summoners.length > 0, 'ElasticDAO: At least 1 summoner required'); for (uint256 i = 0; i < _summoners.length; i += 1) { if (_summoners[i] == address(0)) { revert('ElasticDAO: Summoner address can not be zero address'); } } controller = _controller; deployer = msg.sender; summoners = _summoners; Ecosystem.Instance memory defaults = Ecosystem(_ecosystemModelAddress).deserialize(address(0)); Ecosystem.Instance memory ecosystem = _buildEcosystem(controller, defaults); ecosystemModelAddress = ecosystem.ecosystemModelAddress; bool success = _buildDAO(_summoners, _name, _maxVotingLambda, ecosystem); initialized = true; require(success, 'ElasticDAO: Build DAO Failed'); } function addLiquidityPool(address _poolAddress) external onlyController nonReentrant returns (bool) { liquidityPools.push(_poolAddress); emit LiquidityPoolAdded(_poolAddress); } /** * @notice initializes the token of the DAO * * @param _name - name of the token * @param _symbol - symbol of the token * @param _eByL -the amount of lambda a summoner gets(per ETH) during the seeding phase of the DAO * @param _elasticity the value by which the cost of entering the DAO increases ( on every join ) * @param _k - is the constant token multiplier * it increases the number of tokens that each member of the DAO has with respect to their lambda * @param _maxLambdaPurchase - is the maximum amount of lambda that can be purchased per wallet * * @dev emits ElasticGovernanceTokenDeployed event * @dev * Requirements: * - Only the deployer of the DAO can initialize the Token */ function initializeToken( string memory _name, string memory _symbol, uint256 _eByL, uint256 _elasticity, uint256 _k, uint256 _maxLambdaPurchase ) external onlyBeforeSummoning onlyDeployer nonReentrant { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token.Instance memory token = _buildToken( controller, _name, _symbol, _eByL, _elasticity, _k, _maxLambdaPurchase, ecosystem ); emit ElasticGovernanceTokenDeployed(token.uuid); } /** * @notice this function is to be used for exiting the DAO * for the underlying ETH value of _deltaLambda * * The eth value of _deltaLambda is calculated using: * * eth to be transfered = ( deltaLambda/lambda ) * totalEthInTheDAO * * @param _deltaLambda - the amount of lambda the address exits with * * Requirement: * - ETH transfer must be successful * @dev emits ExitDAO event */ function exit(uint256 _deltaLambda) external onlyAfterSummoning nonReentrant { // burn the shares Token.Instance memory token = _getToken(); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); // eth to be transfered = ( deltaLambda/lambda ) * totalEthInTheDAO uint256 ratioOfShares = ElasticMath.wdiv(_deltaLambda, token.lambda); uint256 ethToBeTransfered = ElasticMath.wmul(ratioOfShares, address(this).balance); // transfer the eth tokenContract.burnShares(msg.sender, _deltaLambda); (bool success, ) = msg.sender.call{ value: ethToBeTransfered }(''); require(success, 'ElasticDAO: Exit Failed'); emit ExitDAO(msg.sender, _deltaLambda, ethToBeTransfered); } /** * @notice this function returns the length of the liquidity pools array * */ function getLiquidityPoolCount() public view returns (uint256) { return liquidityPools.length; } /** * @notice this function is used to join the DAO after it has been summoned * Joining the DAO is syntactically equal to minting _deltaLambda for the function caller. * * Based on the current state of the DAO, capitalDelta, deltaE, mDash are calulated, * after which maxTokenLambda is minted for the address calling the function. * * @dev documentation and further math regarding capitalDelta, deltaE, * mDash can be found at ../libraries/ElasticMath.sol * @dev emits the JoinDAO event * * @dev Requirements: * (The value of maxLambdaPurchase is set during the initialzing of the DAO) * The correct value of ETH, calculated via deltaE, * must be sent in the transaction by the calling address * The token contract should be successfully be able to mint token.makxLambdaPurchase */ function join() external payable onlyAfterSummoning onlyWhenOpen nonReentrant { Token.Instance memory token = _getToken(); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); uint256 capitalDelta = ElasticMath.capitalDelta( // the current totalBalance of the DAO is inclusive of msg.value, // capitalDelta is to be calculated without the msg.value SafeMath.sub(address(this).balance, msg.value), tokenContract.totalSupply() ); uint256 deltaE = ElasticMath.deltaE( token.maxLambdaPurchase, capitalDelta, token.k, token.elasticity, token.lambda, token.m ); require(msg.value >= deltaE, 'ElasticDAO: Incorrect ETH amount'); // mdash uint256 lambdaDash = SafeMath.add(token.maxLambdaPurchase, token.lambda); uint256 mDash = ElasticMath.mDash(lambdaDash, token.lambda, token.m); // serialize the token Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); token.m = mDash; tokenStorage.serialize(token); // tokencontract mint shares bool success = tokenContract.mintShares(msg.sender, token.maxLambdaPurchase); require(success, 'ElasticDAO: Mint Shares Failed during Join'); for (uint256 i = 0; i < liquidityPools.length; i += 1) { IUniswapV2Pair(liquidityPools[i]).sync(); } // return extra ETH if (success && msg.value > deltaE) { (success, ) = msg.sender.call{ value: SafeMath.sub(msg.value, deltaE) }(''); require(success, 'ElasticDAO: TransactionFailed'); } emit JoinDAO(msg.sender, token.maxLambdaPurchase, msg.value); } /** * @notice penalizes @param _addresses with @param _amounts respectively * * @param _addresses - an array of addresses * @param _amounts - an array containing the amounts each address has to be penalized respectively * * @dev Requirement: * - Each address must have a corresponding amount to be penalized with */ function penalize(address[] memory _addresses, uint256[] memory _amounts) external onlyController nonReentrant { require( _addresses.length == _amounts.length, 'ElasticDAO: An amount is required for each address' ); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); for (uint256 i = 0; i < _addresses.length; i += 1) { uint256 lambda = tokenContract.balanceOfInShares(_addresses[i]); if (lambda < _amounts[i]) { if (lambda != 0) { tokenContract.burnShares(_addresses[i], lambda); } FailedToFullyPenalize(_addresses[i], _amounts[i], lambda); } else { tokenContract.burnShares(_addresses[i], _amounts[i]); } } } function removeLiquidityPool(address _poolAddress) external onlyController nonReentrant returns (bool) { for (uint256 i = 0; i < liquidityPools.length; i += 1) { if (liquidityPools[i] == _poolAddress) { liquidityPools[i] = liquidityPools[liquidityPools.length - 1]; liquidityPools.pop(); } } emit LiquidityPoolRemoved(_poolAddress); } /** * @notice rewards @param _addresess with @param _amounts respectively * * @param _addresses - an array of addresses * @param _amounts - an array containing the amounts each address has to be rewarded respectively * * @dev Requirement: * - Each address must have a corresponding amount to be rewarded with */ function reward(address[] memory _addresses, uint256[] memory _amounts) external onlyController nonReentrant { require( _addresses.length == _amounts.length, 'ElasticDAO: An amount is required for each address' ); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); for (uint256 i = 0; i < _addresses.length; i += 1) { tokenContract.mintShares(_addresses[i], _amounts[i]); } } /** * @notice sets the controller of the DAO, * The controller of the DAO handles various responsibilities of the DAO, * such as burning and minting tokens on behalf of the DAO * * @param _controller - the new address of the controller of the DAO * * @dev emits ControllerChanged event * @dev Requirements: * - The controller must not be the 0 address * - The controller of the DAO should successfully be set as the burner of the tokens of the DAO * - The controller of the DAO should successfully be set as the minter of the tokens of the DAO */ function setController(address _controller) external onlyController nonReentrant { require(_controller != address(0), 'ElasticDAO: Address Zero'); controller = _controller; // Update minter / burner ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); bool success = tokenContract.setBurner(controller); require(success, 'ElasticDAO: Set Burner failed during setController'); success = tokenContract.setMinter(controller); require(success, 'ElasticDAO: Set Minter failed during setController'); emit ControllerChanged(controller); } /** * @notice sets the max voting lambda value for the DAO * @param _maxVotingLambda - the value of the maximum amount of lambda that can be used for voting * @dev emits MaxVotingLambdaChanged event */ function setMaxVotingLambda(uint256 _maxVotingLambda) external onlyController nonReentrant { Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoStorage = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoStorage.deserialize(address(this), ecosystem); dao.maxVotingLambda = _maxVotingLambda; daoStorage.serialize(dao); emit MaxVotingLambdaChanged(_maxVotingLambda); } /** * @notice seeds the DAO, * Essentially transferring of ETH by a summoner address, in return for lambda is seeding the DAO, * The lambda receieved is given by: * Lambda = Eth / eByL * * @dev seeding of the DAO occurs after the DAO has been initialized, * and before the DAO has been summoned * @dev emits the SeedDAO event */ function seedSummoning() external payable onlyBeforeSummoning onlySummoners onlyAfterTokenInitialized nonReentrant { Token.Instance memory token = _getToken(); uint256 deltaE = msg.value; uint256 deltaLambda = ElasticMath.wdiv(deltaE, token.eByL); ElasticGovernanceToken(token.uuid).mintShares(msg.sender, deltaLambda); emit SeedDAO(msg.sender, deltaLambda); } /** * @notice summons the DAO, * Summoning the DAO results in all summoners getting _deltaLambda * after which people can enter the DAO using the join function * * @param _deltaLambda - the amount of lambda each summoner address receives * * @dev emits SummonedDAO event * @dev Requirement: * The DAO must be seeded with ETH during the seeding phase * (This is to facilitate capitalDelta calculations after the DAO has been summoned). * * @dev documentation and further math regarding capitalDelta * can be found at ../libraries/ElasticMath.sol */ function summon(uint256 _deltaLambda) external onlyBeforeSummoning onlySummoners nonReentrant { require(address(this).balance > 0, 'ElasticDAO: Please seed DAO with ETH to set ETH:EGT ratio'); Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoContract = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoContract.deserialize(address(this), ecosystem); Token.Instance memory token = Token(ecosystem.tokenModelAddress).deserialize(ecosystem.governanceTokenAddress, ecosystem); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); // number of summoners can not grow unboundly. it is fixed limit. for (uint256 i = 0; i < dao.numberOfSummoners; i += 1) { tokenContract.mintShares(daoContract.getSummoner(dao, i), _deltaLambda); } dao.summoned = true; daoContract.serialize(dao); emit SummonedDAO(msg.sender); } // Getters function getDAO() external view returns (DAO.Instance memory) { return _getDAO(); } function getEcosystem() external view returns (Ecosystem.Instance memory) { return _getEcosystem(); } /** * @dev creates DAO.Instance record * @param _summoners addresses of the summoners * @param _name name of the DAO * @param _ecosystem instance of Ecosystem the DAO uses * @param _maxVotingLambda - the maximum amount of lambda that can be used to vote in the DAO * @return bool true */ function _buildDAO( address[] memory _summoners, string memory _name, uint256 _maxVotingLambda, Ecosystem.Instance memory _ecosystem ) internal returns (bool) { DAO daoStorage = DAO(_ecosystem.daoModelAddress); DAO.Instance memory dao; dao.uuid = address(this); dao.ecosystem = _ecosystem; dao.maxVotingLambda = _maxVotingLambda; dao.name = _name; dao.summoned = false; dao.summoners = _summoners; daoStorage.serialize(dao); return true; } /** * @dev Deploys proxies leveraging the implementation contracts found on the * default Ecosystem.Instance record. * @param _controller the address which can control the core DAO functions * @param _defaults instance of Ecosystem with the implementation addresses * @return ecosystem Ecosystem.Instance */ function _buildEcosystem(address _controller, Ecosystem.Instance memory _defaults) internal returns (Ecosystem.Instance memory ecosystem) { ecosystem.daoAddress = address(this); ecosystem.daoModelAddress = _deployProxy(_defaults.daoModelAddress, _controller); ecosystem.ecosystemModelAddress = _deployProxy(_defaults.ecosystemModelAddress, _controller); ecosystem.governanceTokenAddress = _deployProxy(_defaults.governanceTokenAddress, _controller); ecosystem.tokenHolderModelAddress = _deployProxy( _defaults.tokenHolderModelAddress, _controller ); ecosystem.tokenModelAddress = _deployProxy(_defaults.tokenModelAddress, _controller); Ecosystem(ecosystem.ecosystemModelAddress).serialize(ecosystem); return ecosystem; } /** * @dev creates a Token.Instance record and initializes the ElasticGovernanceToken. * @param _controller the address which can control the core DAO functions * @param _name name of the token * @param _symbol symbol of the token * @param _eByL initial ETH/token ratio * @param _elasticity the percentage by which capitalDelta should increase * @param _k a constant, initially set by the DAO * @param _maxLambdaPurchase maximum amount of lambda (shares) that can be * minted on each call to the join function in ElasticDAO.sol * @param _ecosystem the DAO's ecosystem instance * @return token Token.Instance */ function _buildToken( address _controller, string memory _name, string memory _symbol, uint256 _eByL, uint256 _elasticity, uint256 _k, uint256 _maxLambdaPurchase, Ecosystem.Instance memory _ecosystem ) internal returns (Token.Instance memory token) { token.eByL = _eByL; token.ecosystem = _ecosystem; token.elasticity = _elasticity; token.k = _k; token.lambda = 0; token.m = 1000000000000000000; token.maxLambdaPurchase = _maxLambdaPurchase; token.name = _name; token.symbol = _symbol; token.uuid = _ecosystem.governanceTokenAddress; // initialize the token within the ecosystem return ElasticGovernanceToken(token.uuid).initialize(_controller, _controller, _ecosystem, token); } function _deployProxy(address _implementationAddress, address _owner) internal returns (address) { PProxy proxy = new PProxy(); proxy.setImplementation(_implementationAddress); proxy.setProxyOwner(_owner); return address(proxy); } // Private function _getDAO() internal view returns (DAO.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return DAO(ecosystem.daoModelAddress).deserialize(address(this), ecosystem); } function _getEcosystem() internal view returns (Ecosystem.Instance memory) { return Ecosystem(ecosystemModelAddress).deserialize(address(this)); } function _getToken() internal view returns (Token.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return Token(ecosystem.tokenModelAddress).deserialize(ecosystem.governanceTokenAddress, ecosystem); } receive() external payable {} fallback() external payable {} } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; /** * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing core DAO data * @dev ElasticDAO network contracts can read/write from this contract */ contract DAO is EternalModel, ReentrancyGuard { struct Instance { address uuid; address[] summoners; bool summoned; string name; uint256 maxVotingLambda; uint256 numberOfSummoners; Ecosystem.Instance ecosystem; } event Serialized(address indexed uuid); /** * @dev deserializes Instance struct * @param _uuid - address of the unique user ID * @return record Instance */ function deserialize(address _uuid, Ecosystem.Instance memory _ecosystem) external view returns (Instance memory record) { record.uuid = _uuid; record.ecosystem = _ecosystem; if (_exists(_uuid)) { record.maxVotingLambda = getUint(keccak256(abi.encode(_uuid, 'maxVotingLambda'))); record.name = getString(keccak256(abi.encode(_uuid, 'name'))); record.numberOfSummoners = getUint(keccak256(abi.encode(_uuid, 'numberOfSummoners'))); record.summoned = getBool(keccak256(abi.encode(_uuid, 'summoned'))); } return record; } /** * @dev checks if @param _uuid exists * @param _uuid - address of the unique user ID * @return recordExists bool */ function exists(address _uuid) external view returns (bool) { return _exists(_uuid); } function getSummoner(Instance memory _dao, uint256 _index) external view returns (address) { return getAddress(keccak256(abi.encode(_dao.uuid, 'summoners', _index))); } /** * @dev checks if @param _uuid where _uuid is msg.sender - is a Summoner * @param _dao DAO.Instance * @param _summonerAddress address * @return bool */ function isSummoner(Instance memory _dao, address _summonerAddress) external view returns (bool) { return getBool(keccak256(abi.encode(_dao.uuid, 'summoner', _summonerAddress))); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require(msg.sender == _record.uuid, 'ElasticDAO: Unauthorized'); setUint(keccak256(abi.encode(_record.uuid, 'maxVotingLambda')), _record.maxVotingLambda); setString(keccak256(abi.encode(_record.uuid, 'name')), _record.name); setBool(keccak256(abi.encode(_record.uuid, 'summoned')), _record.summoned); if (_record.summoners.length > 0) { _record.numberOfSummoners = _record.summoners.length; setUint(keccak256(abi.encode(_record.uuid, 'numberOfSummoners')), _record.numberOfSummoners); for (uint256 i = 0; i < _record.numberOfSummoners; i += 1) { setBool(keccak256(abi.encode(_record.uuid, 'summoner', _record.summoners[i])), true); setAddress(keccak256(abi.encode(_record.uuid, 'summoners', i)), _record.summoners[i]); } } setBool(keccak256(abi.encode(_record.uuid, 'exists')), true); emit Serialized(_record.uuid); } function _exists(address _uuid) internal view returns (bool) { return getBool(keccak256(abi.encode(_uuid, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './EternalModel.sol'; /** * @title ElasticDAO ecosystem * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing core dao data * @dev ElasticDAO network contracts can read/write from this contract * @dev Serialize - Translation of data from the concerned struct to key-value pairs * @dev Deserialize - Translation of data from the key-value pairs to a struct */ contract Ecosystem is EternalModel, ReentrancyGuard { struct Instance { address daoAddress; // Models address daoModelAddress; address ecosystemModelAddress; address tokenHolderModelAddress; address tokenModelAddress; // Tokens address governanceTokenAddress; } event Serialized(address indexed _daoAddress); /** * @dev deserializes Instance struct * @param _daoAddress - address of the unique user ID * @return record Instance */ function deserialize(address _daoAddress) external view returns (Instance memory record) { if (_exists(_daoAddress)) { record.daoAddress = _daoAddress; record.daoModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'daoModelAddress')) ); record.ecosystemModelAddress = address(this); record.governanceTokenAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'governanceTokenAddress')) ); record.tokenHolderModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'tokenHolderModelAddress')) ); record.tokenModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'tokenModelAddress')) ); } return record; } /** * @dev checks if @param _daoAddress * @param _daoAddress - address of the unique user ID * @return recordExists bool */ function exists(address _daoAddress) external view returns (bool recordExists) { return _exists(_daoAddress); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { bool recordExists = _exists(_record.daoAddress); require( msg.sender == _record.daoAddress || (_record.daoAddress == address(0) && !recordExists), 'ElasticDAO: Unauthorized' ); setAddress( keccak256(abi.encode(_record.daoAddress, 'daoModelAddress')), _record.daoModelAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'governanceTokenAddress')), _record.governanceTokenAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'tokenHolderModelAddress')), _record.tokenHolderModelAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'tokenModelAddress')), _record.tokenModelAddress ); setBool(keccak256(abi.encode(_record.daoAddress, 'exists')), true); emit Serialized(_record.daoAddress); } function _exists(address _daoAddress) internal view returns (bool recordExists) { return getBool(keccak256(abi.encode(_daoAddress, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; import '../tokens/ElasticGovernanceToken.sol'; /** * @title A data storage for EGT (Elastic Governance Token) * @notice More info about EGT could be found in ./tokens/ElasticGovernanceToken.sol * @notice This contract is used for storing token data * @dev ElasticDAO network contracts can read/write from this contract * Serialize - Translation of data from the concerned struct to key-value pairs * Deserialize - Translation of data from the key-value pairs to a struct */ contract Token is EternalModel, ReentrancyGuard { struct Instance { address uuid; string name; string symbol; uint256 eByL; uint256 elasticity; uint256 k; uint256 lambda; uint256 m; uint256 maxLambdaPurchase; uint256 numberOfTokenHolders; Ecosystem.Instance ecosystem; } event Serialized(address indexed uuid); /** * @dev deserializes Instance struct * @param _uuid - address of the unique user ID * @return record Instance */ function deserialize(address _uuid, Ecosystem.Instance memory _ecosystem) external view returns (Instance memory record) { record.uuid = _uuid; record.ecosystem = _ecosystem; if (_exists(_uuid, _ecosystem.daoAddress)) { record.eByL = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'eByL'))); record.elasticity = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'elasticity')) ); record.k = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'k'))); record.lambda = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'lambda'))); record.m = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'm'))); record.maxLambdaPurchase = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'maxLambdaPurchase')) ); record.name = getString(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'name'))); record.numberOfTokenHolders = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'numberOfTokenHolders')) ); record.symbol = getString( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'symbol')) ); } return record; } function exists(address _uuid, address _daoAddress) external view returns (bool) { return _exists(_uuid, _daoAddress); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require( msg.sender == _record.uuid || (msg.sender == _record.ecosystem.daoAddress && _exists(_record.uuid, _record.ecosystem.daoAddress)), 'ElasticDAO: Unauthorized' ); setString( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'name')), _record.name ); setString( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'symbol')), _record.symbol ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'eByL')), _record.eByL ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'elasticity')), _record.elasticity ); setUint(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'k')), _record.k); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'lambda')), _record.lambda ); setUint(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'm')), _record.m); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'maxLambdaPurchase')), _record.maxLambdaPurchase ); setBool(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'exists')), true); emit Serialized(_record.uuid); } function updateNumberOfTokenHolders(Instance memory _record, uint256 numberOfTokenHolders) external nonReentrant { require( msg.sender == _record.uuid && _exists(_record.uuid, _record.ecosystem.daoAddress), 'ElasticDAO: Unauthorized' ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'numberOfTokenHolders')), numberOfTokenHolders ); } function _exists(address _uuid, address _daoAddress) internal view returns (bool) { return getBool(keccak256(abi.encode(_uuid, _daoAddress, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; import './Token.sol'; /** * @title a data storage for Token holders * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing token data * @dev ElasticDAO network contracts can read/write from this contract * Serialize - Translation of data from the concerned struct to key-value pairs * Deserialize - Translation of data from the key-value pairs to a struct */ contract TokenHolder is EternalModel, ReentrancyGuard { struct Instance { address account; uint256 lambda; Ecosystem.Instance ecosystem; Token.Instance token; } event Serialized(address indexed account, address indexed token); function deserialize( address _account, Ecosystem.Instance memory _ecosystem, Token.Instance memory _token ) external view returns (Instance memory record) { record.account = _account; record.ecosystem = _ecosystem; record.token = _token; if (_exists(_account, _token)) { record.lambda = getUint(keccak256(abi.encode(record.token.uuid, record.account, 'lambda'))); } return record; } function exists(address _account, Token.Instance memory _token) external view returns (bool) { return _exists(_account, _token); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require(msg.sender == _record.token.uuid, 'ElasticDAO: Unauthorized'); setUint(keccak256(abi.encode(_record.token.uuid, _record.account, 'lambda')), _record.lambda); setBool(keccak256(abi.encode(_record.token.uuid, _record.account, 'exists')), true); emit Serialized(_record.account, _record.token.uuid); } function _exists(address _account, Token.Instance memory _token) internal view returns (bool) { return getBool(keccak256(abi.encode(_token.uuid, _account, 'exists'))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.7.2; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'SafeMath: subtraction overflow'); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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 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) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; require(c > 0, 'SafeMath: division by zero'); return c; } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; interface IUniswapV2Pair { function sync() external; } pragma solidity ^0.7.1; import "./PProxyStorage.sol"; contract PProxy is PProxyStorage { bytes32 constant IMPLEMENTATION_SLOT = keccak256(abi.encodePacked("IMPLEMENTATION_SLOT")); bytes32 constant OWNER_SLOT = keccak256(abi.encodePacked("OWNER_SLOT")); modifier onlyProxyOwner() { require(msg.sender == readAddress(OWNER_SLOT), "PProxy.onlyProxyOwner: msg sender not owner"); _; } constructor () public { setAddress(OWNER_SLOT, msg.sender); } function getProxyOwner() public view returns (address) { return readAddress(OWNER_SLOT); } function setProxyOwner(address _newOwner) onlyProxyOwner public { setAddress(OWNER_SLOT, _newOwner); } function getImplementation() public view returns (address) { return readAddress(IMPLEMENTATION_SLOT); } function setImplementation(address _newImplementation) onlyProxyOwner public { setAddress(IMPLEMENTATION_SLOT, _newImplementation); } fallback () external payable { return internalFallback(); } function internalFallback() internal virtual { address contractAddr = readAddress(IMPLEMENTATION_SLOT); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), contractAddr, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; /** * @title Implementation of Eternal Storage for ElasticDAO - * - (https://fravoll.github.io/solidity-patterns/eternal_storage.html) * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing contract network data * @dev ElasticDAO network contracts can read/write from this contract */ contract EternalModel { struct Storage { mapping(bytes32 => address) addressStorage; mapping(bytes32 => bool) boolStorage; mapping(bytes32 => bytes) bytesStorage; mapping(bytes32 => int256) intStorage; mapping(bytes32 => string) stringStorage; mapping(bytes32 => uint256) uIntStorage; } Storage internal s; /** * @notice Getter Functions */ /** * @notice Gets stored contract data in unit256 format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return uint256 _value from storage _key location */ function getUint(bytes32 _key) internal view returns (uint256) { return s.uIntStorage[_key]; } /** * @notice Get stored contract data in string format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return string _value from storage _key location */ function getString(bytes32 _key) internal view returns (string memory) { return s.stringStorage[_key]; } /** * @notice Get stored contract data in address format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return address _value from storage _key location */ function getAddress(bytes32 _key) internal view returns (address) { return s.addressStorage[_key]; } /** * @notice Get stored contract data in bool format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return bool _value from storage _key location */ function getBool(bytes32 _key) internal view returns (bool) { return s.boolStorage[_key]; } /** * @notice Setters Functions */ /** * @notice Store contract data in uint256 format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value uint256 value */ function setUint(bytes32 _key, uint256 _value) internal { s.uIntStorage[_key] = _value; } /** * @notice Store contract data in string format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value string value */ function setString(bytes32 _key, string memory _value) internal { s.stringStorage[_key] = _value; } /** * @notice Store contract data in address format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value address value */ function setAddress(bytes32 _key, address _value) internal { s.addressStorage[_key] = _value; } /** * @notice Store contract data in bool format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value bool value */ function setBool(bytes32 _key, bool _value) internal { s.boolStorage[_key] = _value; } } pragma solidity ^0.7.1; contract PProxyStorage { function readBool(bytes32 _key) public view returns(bool) { return storageRead(_key) == bytes32(uint256(1)); } function setBool(bytes32 _key, bool _value) internal { if(_value) { storageSet(_key, bytes32(uint256(1))); } else { storageSet(_key, bytes32(uint256(0))); } } function readAddress(bytes32 _key) public view returns(address) { return bytes32ToAddress(storageRead(_key)); } function setAddress(bytes32 _key, address _value) internal { storageSet(_key, addressToBytes32(_value)); } function storageRead(bytes32 _key) public view returns(bytes32) { bytes32 value; //solium-disable-next-line security/no-inline-assembly assembly { value := sload(_key) } return value; } function storageSet(bytes32 _key, bytes32 _value) internal { // targetAddress = _address; // No! bytes32 implAddressStorageKey = _key; //solium-disable-next-line security/no-inline-assembly assembly { sstore(implAddressStorageKey, _value) } } function bytes32ToAddress(bytes32 _value) public pure returns(address) { return address(uint160(uint256(_value))); } function addressToBytes32(address _value) public pure returns(bytes32) { return bytes32(uint256(_value)); } }
checks if _uuid where _uuid is msg.sender - is a Summoner _dao DAO.Instance _summonerAddress address return bool/
function isSummoner(Instance memory _dao, address _summonerAddress) external view returns (bool) { return getBool(keccak256(abi.encode(_dao.uuid, 'summoner', _summonerAddress))); }
10,474,447