contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
AddressSet
library AddressSet { struct Set { mapping(address => uint) keyPointers; address[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, address key) internal { require(!exists(self, key), "AddressSet: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, address key) internal { require(exists(self, key), "AddressSet: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { address keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop; } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, address key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(address) { return self.keyList[index]; } }
count
function count(Set storage self) internal view returns(uint) { return(self.keyList.length); }
/** * @notice count the keys. * @param self storage pointer to a Set. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1355, 1467 ] }
4,700
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
AddressSet
library AddressSet { struct Set { mapping(address => uint) keyPointers; address[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, address key) internal { require(!exists(self, key), "AddressSet: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, address key) internal { require(exists(self, key), "AddressSet: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { address keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop; } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, address key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(address) { return self.keyList[index]; } }
exists
function exists(Set storage self, address key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; }
/** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1682, 1882 ] }
4,701
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
AddressSet
library AddressSet { struct Set { mapping(address => uint) keyPointers; address[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, address key) internal { require(!exists(self, key), "AddressSet: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, address key) internal { require(exists(self, key), "AddressSet: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { address keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop; } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, address key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(address) { return self.keyList[index]; } }
keyAtIndex
function keyAtIndex(Set storage self, uint index) internal view returns(address) { return self.keyList[index]; }
/** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 2065, 2196 ] }
4,702
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
add
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 addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 251, 437 ] }
4,703
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
sub
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 on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 707, 848 ] }
4,704
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
sub
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 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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1138, 1335 ] }
4,705
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
mul
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 multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1581, 2057 ] }
4,706
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
div
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 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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 2520, 2657 ] }
4,707
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
div
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 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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 3140, 3490 ] }
4,708
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
mod
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 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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 3942, 4077 ] }
4,709
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
mod
function mod(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), * 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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 4549, 4720 ] }
4,710
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Bytes32Set
library Bytes32Set { struct Set { mapping(bytes32 => uint) keyPointers; bytes32[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, bytes32 key) internal { require(!exists(self, key), "Bytes32Set: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, bytes32 key) internal { require(exists(self, key), "Bytes32Set: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { bytes32 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, bytes32 key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(bytes32) { return self.keyList[index]; } }
insert
function insert(Set storage self, bytes32 key) internal { require(!exists(self, key), "Bytes32Set: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); }
/** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 313, 553 ] }
4,711
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Bytes32Set
library Bytes32Set { struct Set { mapping(bytes32 => uint) keyPointers; bytes32[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, bytes32 key) internal { require(!exists(self, key), "Bytes32Set: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, bytes32 key) internal { require(exists(self, key), "Bytes32Set: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { bytes32 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, bytes32 key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(bytes32) { return self.keyList[index]; } }
remove
function remove(Set storage self, bytes32 key) internal { require(exists(self, key), "Bytes32Set: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { bytes32 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); }
/** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 726, 1246 ] }
4,712
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Bytes32Set
library Bytes32Set { struct Set { mapping(bytes32 => uint) keyPointers; bytes32[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, bytes32 key) internal { require(!exists(self, key), "Bytes32Set: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, bytes32 key) internal { require(exists(self, key), "Bytes32Set: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { bytes32 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, bytes32 key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(bytes32) { return self.keyList[index]; } }
count
function count(Set storage self) internal view returns(uint) { return(self.keyList.length); }
/** * @notice count the keys. * @param self storage pointer to a Set. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1350, 1462 ] }
4,713
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Bytes32Set
library Bytes32Set { struct Set { mapping(bytes32 => uint) keyPointers; bytes32[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, bytes32 key) internal { require(!exists(self, key), "Bytes32Set: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, bytes32 key) internal { require(exists(self, key), "Bytes32Set: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { bytes32 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, bytes32 key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(bytes32) { return self.keyList[index]; } }
exists
function exists(Set storage self, bytes32 key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; }
/** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1679, 1879 ] }
4,714
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Bytes32Set
library Bytes32Set { struct Set { mapping(bytes32 => uint) keyPointers; bytes32[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, bytes32 key) internal { require(!exists(self, key), "Bytes32Set: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, bytes32 key) internal { require(exists(self, key), "Bytes32Set: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { bytes32 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, bytes32 key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(bytes32) { return self.keyList[index]; } }
keyAtIndex
function keyAtIndex(Set storage self, uint index) internal view returns(bytes32) { return self.keyList[index]; }
/** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 2060, 2191 ] }
4,715
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Ownable
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; } }
/** * @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. */
NatSpecMultiLine
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 497, 581 ] }
4,716
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Ownable
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; } }
/** * @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. */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1139, 1292 ] }
4,717
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Ownable
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; } }
/** * @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. */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1442, 1691 ] }
4,718
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 94, 154 ] }
4,719
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 237, 310 ] }
4,720
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 534, 616 ] }
4,721
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 895, 983 ] }
4,722
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 1647, 1726 ] }
4,723
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
transferFrom
function transferFrom(address sender, address recipient, 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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 2039, 2141 ] }
4,724
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
isContract
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 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 * ==== */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 606, 1230 ] }
4,725
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
sendValue
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 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]. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 2160, 2562 ] }
4,726
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
poke
function poke() external distribute ifRunning { _accrueByTime(); }
/************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 8009, 8094 ] }
4,727
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
hodlTIssue
function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); }
/************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 8332, 8756 ] }
4,728
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
sellHodlC
function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); }
/************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 9613, 10225 ] }
4,729
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
buyHodlC
function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); }
/************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 13701, 14347 ] }
4,730
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
cancelSell
function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); }
/************************************************************************************** * Cancel orders **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 18270, 18732 ] }
4,731
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
convertEthToUsd
function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); }
/************************************************************************************** * Prices and quotes **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 19406, 19551 ] }
4,732
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
depositEth
function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); }
/************************************************************************************** * Eth accounts **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 20693, 21009 ] }
4,733
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
rates
function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } }
// Moves forward in 1-day steps to prevent overflow
LineComment
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 21584, 22223 ] }
4,734
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
_accrueByTransaction
function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); }
/************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 22479, 22590 ] }
4,735
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
_makeHodler
function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } }
/************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 23273, 23526 ] }
4,736
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
contractBalanceEth
function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; }
// Courtesy function
LineComment
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 24045, 24145 ] }
4,737
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
distributionsLength
function distributionsLength() public view returns(uint row) { return distribution.length; }
// Distribution queue
LineComment
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 24175, 24272 ] }
4,738
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
hodlerCount
function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); }
// Hodlers in no particular order
LineComment
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 24318, 24411 ] }
4,739
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
sellOrderCount
function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); }
// Open orders, FIFO
LineComment
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 24570, 24668 ] }
4,740
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
userSellOrderCount
function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); }
// open orders by user, FIFO
LineComment
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 25576, 25715 ] }
4,741
HodlDex
HodlDex.sol
0x56b9d34f9f4e4a1a82d847128c1b2264b34d2fae
Solidity
HodlDex
contract HodlDex is Ownable { using Address for address payable; // OpenZeppelin address utility using SafeMath for uint; // OpenZeppelin safeMath utility using Bytes32Set for Bytes32Set.Set; // Unordered key sets using AddressSet for AddressSet.Set; // Unordered address sets using FIFOSet for FIFOSet.FIFO; // FIFO key sets Maker maker = Maker(0x729D19f657BD0614b4985Cf1D82531c67569197B);// EthUsd price Oracle bytes32 constant NULL = bytes32(0); uint constant HODL_PRECISION = 10 ** 10; // HODL token decimal places uint constant USD_PRECISION = 10 ** 18; // Precision for HODL:USD uint constant TOTAL_SUPPLY = 20000000 * (10**10); // Total supply - initially goes to the reserve, which is address(this) uint constant SLEEP_TIME = 30 days; // Grace period before time-based accrual kicks in uint constant DAILY_ACCRUAL_RATE_DECAY = 999999838576236000; // Rate of decay applied daily reduces daily accrual APR to about 5% after 30 years uint constant USD_TXN_ADJUSTMENT = 10**14; // $0.0001 with 18 decimal places of precision - 1/100th of a cent uint public BIRTHDAY; // Now time when the contract was deployed uint public minOrderUsd = 50 * 10 ** 18; // Minimum order size is $50 in USD precision uint public maxOrderUsd = 500 * 10 ** 18; // Maximum order size is $500 is USD precision uint public maxThresholdUsd = 10 * 10 ** 18; // Order limits removed when HODL_USD exceeds $10 uint public maxDistributionUsd = 250 * 10 ** 18; // Maximum distribution value uint public accrualDaysProcessed; // Days of stateful accrual applied uint public distributionNext; // Next distribution to process cursor uint public entropyCounter; // Tally of unique order IDs and distributions generated uint public distributionDelay = 1 days; // Reserve sale distribution delay IERC20 token; // The HODL ERC20 tradable token /************************************************************************************** * @dev The following values are inspected through the rates() function **************************************************************************************/ uint private HODL_USD; // HODL:USD exchange rate last recorded uint private DAILY_ACCRUAL_RATE = 1001900837677230000; // Initial daily accrual is 0.19% (100.19% multiplier) which is about 100% APR struct User { FIFOSet.FIFO sellOrderIdFifo; // User sell orders in no particular order FIFOSet.FIFO buyOrderIdFifo; // User buy orders in no particular order uint balanceEth; uint balanceHodl; } struct SellOrder { address seller; uint volumeHodl; uint askUsd; } struct BuyOrder { address buyer; uint bidEth; } struct Distribution { uint amountEth; uint timeStamp; } mapping(address => User) userStruct; mapping(bytes32 => SellOrder) public sellOrder; mapping(bytes32 => BuyOrder) public buyOrder; FIFOSet.FIFO sellOrderIdFifo; // SELL orders in order of declaration FIFOSet.FIFO buyOrderIdFifo; // BUY orders in order of declaration AddressSet.Set hodlerAddrSet; // Users with a HODL balance > 0 in no particular order Distribution[] public distribution; // Pending distributions in order of declaration modifier ifRunning { require(isRunning(), "Contact is not initialized."); _; } // Deferred pseudo-random reserve sale proceeds distribution modifier distribute { uint distroEth; if(distribution.length > distributionNext) { Distribution storage d = distribution[distributionNext]; if(d.timeStamp.add(distributionDelay) < now) { uint entropy = uint(keccak256(abi.encodePacked(entropyCounter, HODL_USD, maker.read(), blockhash(block.number)))); uint luckyWinnerRow = entropy % hodlerAddrSet.count(); address winnerAddr = hodlerAddrSet.keyAtIndex(luckyWinnerRow); User storage w = userStruct[winnerAddr]; if(convertEthToUsd(d.amountEth) > maxDistributionUsd) { distroEth = convertUsdToEth(maxDistributionUsd); d.amountEth = d.amountEth.sub(distroEth); } else { distroEth = d.amountEth; delete distribution[distributionNext]; distributionNext = distributionNext.add(1); } w.balanceEth = w.balanceEth.add(distroEth); entropyCounter++; emit DistributionAwarded(msg.sender, distributionNext, winnerAddr, distroEth); } } _; } modifier accrueByTime { _accrueByTime(); _; } event DistributionAwarded(address processor, uint indexed index, address indexed recipient, uint amount); event Deployed(address admin); event HodlTIssued(address indexed user, uint amount); event HodlTRedeemed(address indexed user, uint amount); event SellHodlC(address indexed seller, uint quantityHodl, uint lowGas); event SellOrderFilled(address indexed buyer, bytes32 indexed orderId, address indexed seller, uint txnEth, uint txnHodl); event SellOrderOpened(bytes32 indexed orderId, address indexed seller, uint quantityHodl, uint askUsd); event BuyHodlC(address indexed buyer, uint amountEth, uint lowGas); event BuyOrderFilled(address indexed seller, bytes32 indexed orderId, address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderRefunded(address indexed seller, bytes32 indexed orderId, uint refundedEth); event BuyFromReserve(address indexed buyer, uint txnEth, uint txnHodl); event BuyOrderOpened(bytes32 indexed orderedId, address indexed buyer, uint amountEth); event SellOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event BuyOrderCancelled(address indexed userAddr, bytes32 indexed orderId); event UserDepositEth(address indexed user, uint amountEth); event UserWithdrawEth(address indexed user, uint amountEth); event UserInitialized(address admin, address indexed user, uint hodlCR, uint ethCR); event UserUninitialized(address admin, address indexed user, uint hodlDB, uint ethDB); event PriceSet(address admin, uint hodlUsd); event TokenSet(address admin, address hodlToken); event MakerSet(address admin, address maker); constructor() public { userStruct[address(this)].balanceHodl = TOTAL_SUPPLY; BIRTHDAY = now; emit Deployed(msg.sender); } function keyGen() private returns(bytes32 key) { entropyCounter++; return keccak256(abi.encodePacked(address(this), msg.sender, entropyCounter)); } /************************************************************************************** * Anyone can nudge the time-based accrual forward **************************************************************************************/ function poke() external distribute ifRunning { _accrueByTime(); } /************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/ function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender); token.transfer(msg.sender, amount); emit HodlTIssued(msg.sender, amount); } function hodlTRedeem(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.add(amount); t.balanceHodl = t.balanceHodl.sub(amount); _makeHodler(msg.sender); token.transferFrom(msg.sender, address(this), amount); emit HodlTRedeemed(msg.sender, amount); } /************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************************************************************************/ function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd, "Sell order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); quantityHodl = _fillBuyOrders(quantityHodl, lowGas); orderId = _openSellOrder(quantityHodl); _pruneHodler(msg.sender); } function _fillBuyOrders(uint quantityHodl, uint lowGas) private returns(uint remainingHodl) { User storage u = userStruct[msg.sender]; address buyerAddr; bytes32 buyId; uint orderHodl; uint orderEth; uint txnEth; uint txnHodl; while(buyOrderIdFifo.count() > 0 && quantityHodl > 0) { // if(gasleft() < lowGas) return 0; buyId = buyOrderIdFifo.first(); BuyOrder storage o = buyOrder[buyId]; buyerAddr = o.buyer; User storage b = userStruct[o.buyer]; orderEth = o.bidEth; orderHodl = convertEthToHodl(orderEth); if(orderHodl == 0) { // Order is now too small to fill. Refund eth and prune. if(orderEth > 0) { b.balanceEth = b.balanceEth.add(orderEth); emit BuyOrderRefunded(msg.sender, buyId, orderEth); } delete buyOrder[buyId]; buyOrderIdFifo.remove(buyId); b.buyOrderIdFifo.remove(buyId); } else { txnEth = convertHodlToEth(quantityHodl); txnHodl = quantityHodl; if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceHodl = u.balanceHodl.sub(txnHodl, "Insufficient Hodl for computed order volume"); b.balanceHodl = b.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.add(txnEth); o.bidEth = o.bidEth.sub(txnEth, "500 - Insufficient ETH for computed order volume"); quantityHodl = quantityHodl.sub(txnHodl, "500 - Insufficient order Hodl remaining to fill order"); _makeHodler(buyerAddr); _accrueByTransaction(); emit BuyOrderFilled(msg.sender, buyId, o.buyer, txnEth, txnHodl); } } remainingHodl = quantityHodl; } function _openSellOrder(uint quantityHodl) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // Do not allow low gas to result in small sell orders or sell orders to exist while buy orders exist if(convertHodlToUsd(quantityHodl) > minOrderUsd && buyOrderIdFifo.count() == 0) { orderId = keyGen(); (uint askUsd, /*uint accrualRate*/) = rates(); SellOrder storage o = sellOrder[orderId]; sellOrderIdFifo.append(orderId); u.sellOrderIdFifo.append(orderId); o.seller = msg.sender; o.volumeHodl = quantityHodl; o.askUsd = askUsd; u.balanceHodl = u.balanceHodl.sub(quantityHodl, "Insufficient Hodl to open sell order"); emit SellOrderOpened(orderId, msg.sender, quantityHodl, askUsd); } } /************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and returns unspent Eth. **************************************************************************************/ function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Buy order is less than minimum USD value"); require(orderUsd <= orderLimit || orderLimit == 0, "Order exceeds USD limit"); amountEth = _fillSellOrders(amountEth, lowGas); amountEth = _buyFromReserve(amountEth); orderId = _openBuyOrder(amountEth); _makeHodler(msg.sender); } function _fillSellOrders(uint amountEth, uint lowGas) private returns(uint remainingEth) { User storage u = userStruct[msg.sender]; address sellerAddr; bytes32 sellId; uint orderEth; uint orderHodl; uint txnEth; uint txnHodl; while(sellOrderIdFifo.count() > 0 && amountEth > 0) { if(gasleft() < lowGas) return 0; sellId = sellOrderIdFifo.first(); SellOrder storage o = sellOrder[sellId]; sellerAddr = o.seller; User storage s = userStruct[sellerAddr]; orderHodl = o.volumeHodl; orderEth = convertHodlToEth(orderHodl); txnEth = amountEth; txnHodl = convertEthToHodl(txnEth); if(orderEth < txnEth) { txnEth = orderEth; txnHodl = orderHodl; } u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from sell order"); s.balanceEth = s.balanceEth.add(txnEth); u.balanceHodl = u.balanceHodl.add(txnHodl); o.volumeHodl = o.volumeHodl.sub(txnHodl, "500 - order has insufficient Hodl for computed volume"); amountEth = amountEth.sub(txnEth, "500 - overspent buy order"); _accrueByTransaction(); emit SellOrderFilled(msg.sender, sellId, o.seller, txnEth, txnHodl); if(o.volumeHodl == 0) { delete sellOrder[sellId]; sellOrderIdFifo.remove(sellId); s.sellOrderIdFifo.remove(sellId); _pruneHodler(sellerAddr); } } remainingEth = amountEth; } function _buyFromReserve(uint amountEth) private returns(uint remainingEth) { uint txnHodl; uint txnEth; if(amountEth > 0) { Distribution memory d; User storage u = userStruct[msg.sender]; User storage r = userStruct[address(this)]; txnHodl = (convertEthToHodl(amountEth) <= r.balanceHodl) ? convertEthToHodl(amountEth) : r.balanceHodl; if(txnHodl > 0) { txnEth = convertHodlToEth(txnHodl); r.balanceHodl = r.balanceHodl.sub(txnHodl, "500 - reserve has insufficient Hodl for computed volume"); u.balanceHodl = u.balanceHodl.add(txnHodl); u.balanceEth = u.balanceEth.sub(txnEth, "Insufficient funds to buy from reserve"); d.amountEth = txnEth; d.timeStamp = now; distribution.push(d); amountEth = amountEth.sub(txnEth, "500 - buy order has insufficient ETH to complete reserve purchase"); _accrueByTransaction(); emit BuyFromReserve(msg.sender, txnEth, txnHodl); } } remainingEth = amountEth; } function _openBuyOrder(uint amountEth) private returns(bytes32 orderId) { User storage u = userStruct[msg.sender]; // do not allow low gas to open a small buy order or buy orders to exist while sell orders exist if(convertEthToUsd(amountEth) > minOrderUsd && sellOrderIdFifo.count() == 0) { orderId = keyGen(); BuyOrder storage o = buyOrder[orderId]; buyOrderIdFifo.append(orderId); u.buyOrderIdFifo.append(orderId); u.balanceEth = u.balanceEth.sub(amountEth, "Insufficient funds to open buy order"); o.bidEth = amountEth; o.buyer = msg.sender; emit BuyOrderOpened(orderId, msg.sender, amountEth); } } /************************************************************************************** * Cancel orders **************************************************************************************/ function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u.sellOrderIdFifo.remove(orderId); sellOrderIdFifo.remove(orderId); emit SellOrderCancelled(msg.sender, orderId); } function cancelBuy(bytes32 orderId) external distribute accrueByTime ifRunning { BuyOrder storage o = buyOrder[orderId]; User storage u = userStruct[o.buyer]; require(o.buyer == msg.sender, "Sender is not the buyer."); u.balanceEth = u.balanceEth.add(o.bidEth); u.buyOrderIdFifo.remove(orderId); buyOrderIdFifo.remove(orderId); emit BuyOrderCancelled(msg.sender, orderId); } /************************************************************************************** * Prices and quotes **************************************************************************************/ function convertEthToUsd(uint amtEth) public view returns(uint inUsd) { inUsd = amtEth.mul(maker.read()).div(USD_PRECISION); } function convertUsdToEth(uint amtUsd) public view returns(uint inEth) { inEth = amtUsd.mul(USD_PRECISION).div(convertEthToUsd(USD_PRECISION)); } function convertHodlToUsd(uint amtHodl) public view returns(uint inUsd) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inUsd = amtHodl.mul(_hodlUsd).div(HODL_PRECISION); } function convertUsdToHodl(uint amtUsd) public view returns(uint inHodl) { (uint _hodlUsd, /*uint _accrualRate*/) = rates(); inHodl = amtUsd.mul(HODL_PRECISION).div(_hodlUsd); } function convertEthToHodl(uint amtEth) public view returns(uint inHodl) { uint inUsd = convertEthToUsd(amtEth); inHodl = convertUsdToHodl(inUsd); } function convertHodlToEth(uint amtHodl) public view returns(uint inEth) { uint inUsd = convertHodlToUsd(amtHodl); inEth = convertUsdToEth(inUsd); } /************************************************************************************** * Eth accounts **************************************************************************************/ function depositEth() external accrueByTime distribute ifRunning payable { require(msg.value > 0, "You must send Eth to this function"); User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.add(msg.value); emit UserDepositEth(msg.sender, msg.value); } function withdrawEth(uint amount) external accrueByTime distribute ifRunning { User storage u = userStruct[msg.sender]; u.balanceEth = u.balanceEth.sub(amount); emit UserWithdrawEth(msg.sender, amount); msg.sender.sendValue(amount); } /************************************************************************************** * Accrual and rate decay over time **************************************************************************************/ // Moves forward in 1-day steps to prevent overflow function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed); if(daysUnprocessed > 0) { hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION); dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION); } } } /************************************************************************************** * Stateful activity-based and time-based rate adjustments **************************************************************************************/ function _accrueByTransaction() private { HODL_USD = HODL_USD.add(USD_TXN_ADJUSTMENT); } function _accrueByTime() private returns(uint hodlUsdNow, uint dailyAccrualRateNow) { (hodlUsdNow, dailyAccrualRateNow) = rates(); if(hodlUsdNow != HODL_USD || dailyAccrualRateNow != DAILY_ACCRUAL_RATE) { HODL_USD = hodlUsdNow; DAILY_ACCRUAL_RATE = dailyAccrualRateNow; accrualDaysProcessed = accrualDaysProcessed.add(1); } } /************************************************************************************** * Add and remove from hodlerAddrSet based on total HODLC owned/controlled **************************************************************************************/ function _makeHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) >= minOrderUsd) { if(!hodlerAddrSet.exists(user)) hodlerAddrSet.insert(user); } } function _pruneHodler(address user) private { User storage u = userStruct[user]; if(convertHodlToUsd(u.balanceHodl) < minOrderUsd) { if(hodlerAddrSet.exists(user)) hodlerAddrSet.remove(user); } } /************************************************************************************** * View functions to enumerate the state **************************************************************************************/ // Courtesy function function contractBalanceEth() public view returns(uint ineth) { return address(this).balance; } // Distribution queue function distributionsLength() public view returns(uint row) { return distribution.length; } // Hodlers in no particular order function hodlerCount() public view returns(uint count) { return hodlerAddrSet.count(); } function hodlerAtIndex(uint index) public view returns(address userAddr) { return hodlerAddrSet.keyAtIndex(index); } // Open orders, FIFO function sellOrderCount() public view returns(uint count) { return sellOrderIdFifo.count(); } function sellOrderFirst() public view returns(bytes32 orderId) { return sellOrderIdFifo.first(); } function sellOrderLast() public view returns(bytes32 orderId) { return sellOrderIdFifo.last(); } function sellOrderIterate(bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return (sellOrderIdFifo.previous(orderId), sellOrderIdFifo.next(orderId)); } function buyOrderCount() public view returns(uint count) { return buyOrderIdFifo.count(); } function buyOrderFirst() public view returns(bytes32 orderId) { return buyOrderIdFifo.first(); } function buyOrderLast() public view returns(bytes32 orderId) { return buyOrderIdFifo.last(); } function buyOrderIterate(bytes32 orderId) public view returns(bytes32 ifBefore, bytes32 idAfter) { return(buyOrderIdFifo.previous(orderId), buyOrderIdFifo.next(orderId)); } // open orders by user, FIFO function userSellOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].sellOrderIdFifo.count(); } function userSellOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.first(); } function userSellOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].sellOrderIdFifo.last(); } function userSellOrderIterate(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].sellOrderIdFifo.previous(orderId), userStruct[userAddr].sellOrderIdFifo.next(orderId)); } function userBuyOrderCount(address userAddr) public view returns(uint count) { return userStruct[userAddr].buyOrderIdFifo.count(); } function userBuyOrderFirst(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.first(); } function userBuyOrderLast(address userAddr) public view returns(bytes32 orderId) { return userStruct[userAddr].buyOrderIdFifo.last(); } function userBuyOrderIdFifo(address userAddr, bytes32 orderId) public view returns(bytes32 idBefore, bytes32 idAfter) { return(userStruct[userAddr].buyOrderIdFifo.previous(orderId), userStruct[userAddr].buyOrderIdFifo.next(orderId)); } function user(address userAddr) public view returns(uint balanceEth, uint balanceHodl) { User storage u = userStruct[userAddr]; return(u.balanceEth, u.balanceHodl); } function isAccruing() public view returns(bool accruing) { return now > BIRTHDAY.add(SLEEP_TIME); } function isRunning() public view returns(bool running) { return owner() == address(0); } function orderLimit() public view returns(uint limitUsd) { // get selling price in USD (uint askUsd, /*uint accrualRate*/) = rates(); return (askUsd > maxThresholdUsd) ? 0 : maxOrderUsd; } function makerAddr() public view returns(address) { return address(maker); } function hodlTAddr() public view returns(address) { return address(token); } /************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/ function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); } function initResetUser(address userAddr) external onlyOwner { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; r.balanceHodl = r.balanceHodl.add(u.balanceHodl); if(u.balanceEth > 0) msg.sender.transfer(u.balanceEth); emit UserUninitialized(msg.sender, userAddr, u.balanceHodl, u.balanceEth); delete userStruct[userAddr]; _pruneHodler(userAddr); } function initSetHodlTAddress(IERC20 hodlToken) external onlyOwner { /// @dev Transfer the total supply of these tokens to this contract during migration token = IERC20(hodlToken); emit TokenSet(msg.sender, address(token)); } function initSetHodlUsd(uint price) external onlyOwner { HODL_USD = price; emit PriceSet(msg.sender, price); } function initSetMaker(address _maker) external onlyOwner { maker = Maker(_maker); emit MakerSet(msg.sender, _maker); } function renounceOwnership() public override onlyOwner { require(token.balanceOf(address(this)) == TOTAL_SUPPLY, "Assign the HoldT supply to this contract before trading starts"); Ownable.renounceOwnership(); } }
initUser
function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl.sub(hodl); _makeHodler(userAddr); emit UserInitialized(msg.sender, userAddr, hodl, msg.value); }
/************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://79694aa4d1d0a87f083e18c227af8c99a7024083b34b5be57d06a5a91e1162a4
{ "func_code_index": [ 28052, 28496 ] }
4,742
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Proxy
abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
/** * @dev Fallback function. * Implemented entirely in `_fallback`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 118, 178 ] }
4,743
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Proxy
abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
_implementation
function _implementation() internal virtual view returns (address);
/** * @return The Address of the implementation. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 247, 318 ] }
4,744
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Proxy
abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
_delegate
function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } }
/** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 615, 1647 ] }
4,745
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Proxy
abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
_willFallback
function _willFallback() internal virtual {}
/** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 1865, 1913 ] }
4,746
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Proxy
abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
_fallback
function _fallback() internal { _willFallback(); _delegate(_implementation()); }
/** * @dev fallback implementation. * Extracted to enable manual triggering. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 2015, 2119 ] }
4,747
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
isContract
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 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 * ==== */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 589, 1203 ] }
4,748
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
sendValue
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 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]. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 2117, 2513 ] }
4,749
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCall
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
/** * @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._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 3251, 3426 ] }
4,750
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCall
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 with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 3645, 3843 ] }
4,751
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCallWithValue
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-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._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 4202, 4430 ] }
4,752
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCallWithValue
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); }
/** * @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._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 4675, 4992 ] }
4,753
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
UpgradeabilityProxy
contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param implementationContract Address of the initial implementation. */ constructor(address implementationContract) public { assert( IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation") ); _setImplementation(implementationContract); } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
/** * @notice This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/UpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Use Address utility library from the latest OpenZeppelin (5/13/20) */
NatSpecMultiLine
_implementation
function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } }
/** * @dev Returns the current implementation. * @return impl Address of the current implementation */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 1057, 1246 ] }
4,754
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
UpgradeabilityProxy
contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param implementationContract Address of the initial implementation. */ constructor(address implementationContract) public { assert( IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation") ); _setImplementation(implementationContract); } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
/** * @notice This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/UpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Use Address utility library from the latest OpenZeppelin (5/13/20) */
NatSpecMultiLine
_upgradeTo
function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); }
/** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 1388, 1544 ] }
4,755
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
UpgradeabilityProxy
contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param implementationContract Address of the initial implementation. */ constructor(address implementationContract) public { assert( IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation") ); _setImplementation(implementationContract); } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
/** * @notice This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/UpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Use Address utility library from the latest OpenZeppelin (5/13/20) */
NatSpecMultiLine
_setImplementation
function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } }
/** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 1688, 2036 ] }
4,756
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
AdminUpgradeabilityProxy
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } }
/** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */
NatSpecMultiLine
admin
function admin() external view returns (address) { return _admin(); }
/** * @return The address of the proxy admin. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 1437, 1522 ] }
4,757
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
AdminUpgradeabilityProxy
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } }
/** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */
NatSpecMultiLine
implementation
function implementation() external view returns (address) { return _implementation(); }
/** * @return The address of the implementation. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 1591, 1694 ] }
4,758
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
AdminUpgradeabilityProxy
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } }
/** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */
NatSpecMultiLine
changeAdmin
function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); }
/** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 1879, 2155 ] }
4,759
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
AdminUpgradeabilityProxy
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } }
/** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */
NatSpecMultiLine
upgradeTo
function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); }
/** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 2348, 2461 ] }
4,760
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
AdminUpgradeabilityProxy
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } }
/** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */
NatSpecMultiLine
upgradeToAndCall
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); }
/** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 3002, 3412 ] }
4,761
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
AdminUpgradeabilityProxy
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } }
/** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */
NatSpecMultiLine
_admin
function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } }
/** * @return adm The admin slot. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 3466, 3628 ] }
4,762
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
AdminUpgradeabilityProxy
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } }
/** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */
NatSpecMultiLine
_setAdmin
function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } }
/** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 3751, 3909 ] }
4,763
FiatTokenProxy
FiatTokenProxy.sol
0x2c9e7a3009f4a1c289a3608067d6f13a39e362d6
Solidity
AdminUpgradeabilityProxy
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } }
/** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */
NatSpecMultiLine
_willFallback
function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); }
/** * @dev Only fall back when the sender is not the admin. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://805b1c87d32334e4682f629e60368cb513ac343a0470ae5bcd139e1141e3ebed
{ "func_code_index": [ 3989, 4203 ] }
4,764
wBTClfBTCLPTokenSharePool
contracts/IRewardDistributionRecipient.sol
0x4db2fa451e1051a013a42fad98b04c2ab81043af
Solidity
wBTClfBTCLPTokenSharePool
contract wBTClfBTCLPTokenSharePool is LPTokenWrapper, IRewardDistributionRecipient, Operator { using SafeMath for uint256; using SafeERC20 for IERC20; address public boardroom; address public share; // lift uint256 public DURATION = 730 days; uint256 public starttime; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lockoutPeriod = 30; // days stuck for that free genesis money uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public lockedOutDate; 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); constructor( address _boardroom, address _share, address _lptoken, uint256 _starttime ) { boardroom = _boardroom; share = _share; lpt = _lptoken; starttime = _starttime; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function daysElapsed() external view returns (uint256) { return ((block.timestamp - lockedOutDate[msg.sender]) / 60 / 60 / 24); } function rewardPerToken() public view 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 returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, 'wBTClkBTCLPTokenSharePool: Cannot stake 0'); super.stake(msg.sender, msg.sender, amount); emit Staked(msg.sender, amount); } function stakeLP(address staker, address from, uint256 amount, bool lockout) external updateReward(staker) { require(amount > 0, 'wBTClfBTCLPTokenSharePool: cannot stake 0'); if(lockout) lockedOutDate[msg.sender] = block.timestamp; super.stake(staker, from, amount); emit Staked(staker, amount); } function withdraw(uint256 amount) public override updateReward(msg.sender) { require(amount > 0, 'wBTClkBTCLPTokenSharePool: Cannot withdraw 0'); require(amount <= super.balanceOf(msg.sender), 'wBTClkBTCLPTokenSharePool: Cannot withdraw more than staked'); require(((lockedOutDate[msg.sender] - block.timestamp) / 60 / 60 / 24) >= lockoutPeriod, 'lfBTCLiftLPTokenSharePool: still in lockout period'); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); stakeInBoardroom(); } function stakeInBoardroom() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; IERC20(share).approve(boardroom, reward); IBoardroom(boardroom).stakeShareForThirdParty(msg.sender, address(this), reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } //EVERY PROJECT I HAVE SEEN HAS A NEED TO NUKE THEIR LP AT SOME POINT function burnRewards() external onlyOwner { IBasisAsset(share).burn(IERC20(share).balanceOf(address(this))); } // supports the evolution of the boardroom without ending staking function updateBoardroom(address newBoardroom) external onlyOwner { boardroom = newBoardroom; } function cleanUpDust(uint256 amount, address tokenAddress, address sendTo) onlyOperator public { require(tokenAddress != lpt, 'If you need to withdrawl lpt use the DAO to migrate to a new contract'); IERC20(tokenAddress).safeTransfer(sendTo, amount); } function updateStakingToken(address newToken) public onlyOperator { lpt = newToken; } }
stake
function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, 'wBTClkBTCLPTokenSharePool: Cannot stake 0'); super.stake(msg.sender, msg.sender, amount); emit Staked(msg.sender, amount); }
// stake visibility is public as overriding LPTokenWrapper's stake() function
LineComment
v0.7.0+commit.9e61f92b
{ "func_code_index": [ 2627, 2897 ] }
4,765
wBTClfBTCLPTokenSharePool
contracts/IRewardDistributionRecipient.sol
0x4db2fa451e1051a013a42fad98b04c2ab81043af
Solidity
wBTClfBTCLPTokenSharePool
contract wBTClfBTCLPTokenSharePool is LPTokenWrapper, IRewardDistributionRecipient, Operator { using SafeMath for uint256; using SafeERC20 for IERC20; address public boardroom; address public share; // lift uint256 public DURATION = 730 days; uint256 public starttime; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lockoutPeriod = 30; // days stuck for that free genesis money uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public lockedOutDate; 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); constructor( address _boardroom, address _share, address _lptoken, uint256 _starttime ) { boardroom = _boardroom; share = _share; lpt = _lptoken; starttime = _starttime; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function daysElapsed() external view returns (uint256) { return ((block.timestamp - lockedOutDate[msg.sender]) / 60 / 60 / 24); } function rewardPerToken() public view 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 returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, 'wBTClkBTCLPTokenSharePool: Cannot stake 0'); super.stake(msg.sender, msg.sender, amount); emit Staked(msg.sender, amount); } function stakeLP(address staker, address from, uint256 amount, bool lockout) external updateReward(staker) { require(amount > 0, 'wBTClfBTCLPTokenSharePool: cannot stake 0'); if(lockout) lockedOutDate[msg.sender] = block.timestamp; super.stake(staker, from, amount); emit Staked(staker, amount); } function withdraw(uint256 amount) public override updateReward(msg.sender) { require(amount > 0, 'wBTClkBTCLPTokenSharePool: Cannot withdraw 0'); require(amount <= super.balanceOf(msg.sender), 'wBTClkBTCLPTokenSharePool: Cannot withdraw more than staked'); require(((lockedOutDate[msg.sender] - block.timestamp) / 60 / 60 / 24) >= lockoutPeriod, 'lfBTCLiftLPTokenSharePool: still in lockout period'); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); stakeInBoardroom(); } function stakeInBoardroom() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; IERC20(share).approve(boardroom, reward); IBoardroom(boardroom).stakeShareForThirdParty(msg.sender, address(this), reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } //EVERY PROJECT I HAVE SEEN HAS A NEED TO NUKE THEIR LP AT SOME POINT function burnRewards() external onlyOwner { IBasisAsset(share).burn(IERC20(share).balanceOf(address(this))); } // supports the evolution of the boardroom without ending staking function updateBoardroom(address newBoardroom) external onlyOwner { boardroom = newBoardroom; } function cleanUpDust(uint256 amount, address tokenAddress, address sendTo) onlyOperator public { require(tokenAddress != lpt, 'If you need to withdrawl lpt use the DAO to migrate to a new contract'); IERC20(tokenAddress).safeTransfer(sendTo, amount); } function updateStakingToken(address newToken) public onlyOperator { lpt = newToken; } }
burnRewards
function burnRewards() external onlyOwner { IBasisAsset(share).burn(IERC20(share).balanceOf(address(this))); }
//EVERY PROJECT I HAVE SEEN HAS A NEED TO NUKE THEIR LP AT SOME POINT
LineComment
v0.7.0+commit.9e61f92b
{ "func_code_index": [ 5328, 5463 ] }
4,766
wBTClfBTCLPTokenSharePool
contracts/IRewardDistributionRecipient.sol
0x4db2fa451e1051a013a42fad98b04c2ab81043af
Solidity
wBTClfBTCLPTokenSharePool
contract wBTClfBTCLPTokenSharePool is LPTokenWrapper, IRewardDistributionRecipient, Operator { using SafeMath for uint256; using SafeERC20 for IERC20; address public boardroom; address public share; // lift uint256 public DURATION = 730 days; uint256 public starttime; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lockoutPeriod = 30; // days stuck for that free genesis money uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public lockedOutDate; 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); constructor( address _boardroom, address _share, address _lptoken, uint256 _starttime ) { boardroom = _boardroom; share = _share; lpt = _lptoken; starttime = _starttime; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function daysElapsed() external view returns (uint256) { return ((block.timestamp - lockedOutDate[msg.sender]) / 60 / 60 / 24); } function rewardPerToken() public view 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 returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, 'wBTClkBTCLPTokenSharePool: Cannot stake 0'); super.stake(msg.sender, msg.sender, amount); emit Staked(msg.sender, amount); } function stakeLP(address staker, address from, uint256 amount, bool lockout) external updateReward(staker) { require(amount > 0, 'wBTClfBTCLPTokenSharePool: cannot stake 0'); if(lockout) lockedOutDate[msg.sender] = block.timestamp; super.stake(staker, from, amount); emit Staked(staker, amount); } function withdraw(uint256 amount) public override updateReward(msg.sender) { require(amount > 0, 'wBTClkBTCLPTokenSharePool: Cannot withdraw 0'); require(amount <= super.balanceOf(msg.sender), 'wBTClkBTCLPTokenSharePool: Cannot withdraw more than staked'); require(((lockedOutDate[msg.sender] - block.timestamp) / 60 / 60 / 24) >= lockoutPeriod, 'lfBTCLiftLPTokenSharePool: still in lockout period'); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); stakeInBoardroom(); } function stakeInBoardroom() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; IERC20(share).approve(boardroom, reward); IBoardroom(boardroom).stakeShareForThirdParty(msg.sender, address(this), reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } //EVERY PROJECT I HAVE SEEN HAS A NEED TO NUKE THEIR LP AT SOME POINT function burnRewards() external onlyOwner { IBasisAsset(share).burn(IERC20(share).balanceOf(address(this))); } // supports the evolution of the boardroom without ending staking function updateBoardroom(address newBoardroom) external onlyOwner { boardroom = newBoardroom; } function cleanUpDust(uint256 amount, address tokenAddress, address sendTo) onlyOperator public { require(tokenAddress != lpt, 'If you need to withdrawl lpt use the DAO to migrate to a new contract'); IERC20(tokenAddress).safeTransfer(sendTo, amount); } function updateStakingToken(address newToken) public onlyOperator { lpt = newToken; } }
updateBoardroom
function updateBoardroom(address newBoardroom) external onlyOwner { boardroom = newBoardroom; }
// supports the evolution of the boardroom without ending staking
LineComment
v0.7.0+commit.9e61f92b
{ "func_code_index": [ 5537, 5656 ] }
4,767
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
add
function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); }
// Add a new token to the pool. Can only be called by the owner.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 3183, 3989 ] }
4,768
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
claim
function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); }
// claim rewards
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 5987, 6611 ] }
4,769
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
deposit
function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); }
// Deposit tokens to liquidity mining for reward token allocation.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 6684, 7348 ] }
4,770
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
withdrawEmergency
function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; }
// Withdraw without caring about rewards. EMERGENCY ONLY.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 7412, 7797 ] }
4,771
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
reallocatePool
function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); }
// Update the given pool's reward token allocation point. Can only be called by the owner.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 7894, 8335 ] }
4,772
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
setRewardPerBlock
function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); }
// Set reward per block. Can only be called by the owner.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 8399, 8573 ] }
4,773
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
setUnlocks
function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } }
// Set unlocks infos - block number and quota.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 8626, 9010 ] }
4,774
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
withdraw
function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); }
// Withdraw tokens from rewardToken liquidity mining.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 9070, 9682 ] }
4,775
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
poolCount
function poolCount() external view returns (uint256) { return poolInfo.length; }
// Number of pools.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 9708, 9804 ] }
4,776
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
massUpdatePools
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
// Update reward variables for all pools. Be careful of gas spending!
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 9979, 10158 ] }
4,777
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
updatePool
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; }
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 10227, 11153 ] }
4,778
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
isTokenAdded
function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); }
// Return bool - is token added or not
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 11198, 11443 ] }
4,779
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
_safeRewardTransfer
function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } }
// Safe rewardToken transfer function.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 11488, 11787 ] }
4,780
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
setMigrator
function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); }
// Set the migrator contract. Can only be called by the owner.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 11856, 12004 ] }
4,781
LiquidityMining
contracts/LiquidityMining.sol
0x8a5827ad1f28d3f397b748ce89895e437b8ef90d
Solidity
LiquidityMining
contract LiquidityMining is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user per pool. struct UserPoolInfo { uint256 amount; // How many tokens the user has provided. uint256 accruedReward; // Reward accrued. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 accRewardPerShare; // Accumulated reward token per share, times 1e12. See below. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that reward token distribution occurs. } struct UnlockInfo { uint256 block; uint256 quota; } // The reward token token IERC20 public rewardToken; // Reservoir address. address public reservoir; // rewardToken tokens created per block. uint256 public rewardPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Blocks and quotas of rewards unlocks UnlockInfo[] public unlocks; uint256 public unlocksTotalQuotation; // Accumulated rewards mapping(address => uint256) public rewards; // Claimed rewards mapping(address => uint256) public claimedRewards; // Info of each pool. PoolInfo[] public poolInfo; // Pid of each pool by its address mapping(address => uint256) public poolPidByAddress; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserPoolInfo)) public userPoolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // The block number when rewardToken mining end. uint256 public endBlock; event TokenAdded( address indexed token, uint256 indexed pid, uint256 allocPoint ); event Claimed(address indexed user, uint256 amount); event Deposited(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdrawn( address indexed user, uint256 indexed pid, uint256 amount ); event TokenMigrated( address indexed oldtoken, address indexed newToken, uint256 indexed pid ); event RewardPerBlockSet(uint256 rewardPerBlock); event TokenSet( address indexed token, uint256 indexed pid, uint256 allocPoint ); event MigratorSet(address indexed migrator); event Withdrawn(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _rewardToken, address _reservoir, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) { rewardToken = _rewardToken; reservoir = _reservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Add a new token to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = poolInfo.length; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 }) ); poolPidByAddress[address(_token)] = pid; emit TokenAdded(address(_token), pid, _allocPoint); } function accrueReward(uint256 _pid) internal { UserPoolInfo memory userPool = userPoolInfo[_pid][msg.sender]; if (userPool.amount == 0) { return; } rewards[msg.sender] = rewards[msg.sender].add( calcReward(poolInfo[_pid], userPool).sub(userPool.accruedReward) ); } function calcReward(PoolInfo memory pool, UserPoolInfo memory userPool) internal returns(uint256){ return userPool.amount.mul(pool.accRewardPerShare).div(1e12); } function getPendingReward(uint256 _pid, address _user) external view returns(uint256 total, uint256 unlocked) { PoolInfo memory pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock < startBlock) { return (0, 0); } if (currentBlock > endBlock) { currentBlock = endBlock; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { return (0, 0); } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); UserPoolInfo memory userPool = userPoolInfo[_pid][_user]; total = userPool.amount .mul(accRewardPerShare) .div(1e12) .sub(userPool.accruedReward); unlocked = calcUnlocked(total); } function calcUnlocked(uint256 reward) public view returns(uint256 claimable) { uint256 i; for (i = 0; i < unlocks.length; ++i) { if (block.number < unlocks[i].block) { continue; } claimable = claimable.add( reward.mul(unlocks[i].quota) .div(unlocksTotalQuotation) ); } } // claim rewards function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]); if (unlocked > 0) { _safeRewardTransfer(msg.sender, unlocked); } claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked); emit Claimed(msg.sender, unlocked); } // Deposit tokens to liquidity mining for reward token allocation. function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function withdrawEmergency(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), userPool.amount); emit EmergencyWithdrawn(msg.sender, _pid, userPool.amount); userPool.amount = 0; userPool.accruedReward = 0; } // Update the given pool's reward token allocation point. Can only be called by the owner. function reallocatePool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; emit TokenSet(address(poolInfo[_pid].token), _pid, _allocPoint); } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit RewardPerBlockSet(_rewardPerBlock); } // Set unlocks infos - block number and quota. function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } } // Withdraw tokens from rewardToken liquidity mining. function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); } // Number of pools. function poolCount() external view returns (uint256) { return poolInfo.length; } function unlockCount() external view returns (uint256) { return unlocks.length; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 currentBlock = block.number; if (currentBlock > endBlock) { currentBlock = endBlock; } if (currentBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.token.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = currentBlock; return; } uint256 blockLasted = currentBlock.sub(pool.lastRewardBlock); uint256 reward = blockLasted.mul(rewardPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); rewardToken.transferFrom(reservoir, address(this), reward); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = currentBlock; } // Return bool - is token added or not function isTokenAdded(IERC20 _token) public view returns (bool) { uint256 pid = poolPidByAddress[address(_token)]; return poolInfo.length > pid && address(poolInfo[pid].token) == address(_token); } // Safe rewardToken transfer function. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 balance = rewardToken.balanceOf(address(this)); if (_amount > balance) { rewardToken.transfer(_to, balance); } else { rewardToken.transfer(_to, _amount); } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) external onlyOwner { migrator = _migrator; emit MigratorSet(address(_migrator)); } // Migrate token to another lp contract. Can be called by anyone. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); } function getAllPools() external view returns (PoolInfo[] memory) { return poolInfo; } function getAllUnlocks() external view returns (UnlockInfo[] memory) { return unlocks; } }
migrate
function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); }
// Migrate token to another lp contract. Can be called by anyone.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 12076, 12718 ] }
4,782
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
__PaymentSplitter_init
function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); }
/** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 1066, 1280 ] }
4,783
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
/** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 2215, 2319 ] }
4,784
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
totalShares
function totalShares() public view returns (uint256) { return _totalShares; }
/** * @dev Getter for the total shares held by payees. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 2397, 2493 ] }
4,785
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
totalReleased
function totalReleased() public view returns (uint256) { return _totalReleased; }
/** * @dev Getter for the total amount of Ether already released. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 2582, 2682 ] }
4,786
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
totalReleased
function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; }
/** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 2834, 2969 ] }
4,787
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
shares
function shares(address account) public view returns (uint256) { return _shares[account]; }
/** * @dev Getter for the amount of shares held by an account. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3055, 3165 ] }
4,788
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
released
function released(address account) public view returns (uint256) { return _released[account]; }
/** * @dev Getter for the amount of Ether already released to a payee. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3259, 3373 ] }
4,789
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
released
function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; }
/** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3537, 3688 ] }
4,790
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
payee
function payee(uint256 index) public view returns (address) { return _payees[index]; }
/** * @dev Getter for the address of the payee number `index`. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3774, 3879 ] }
4,791
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
release
function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); }
/** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4074, 4656 ] }
4,792
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
release
function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); }
/** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4919, 5587 ] }
4,793
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
_pendingPayment
function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; }
/** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 5760, 6013 ] }
4,794
ERC1155PaymentSplitterUAEUpgradeable
contracts/additional/PaymentSplitterUpgradeable.sol
0x14d1170ce870a7dfb5ea570977b2baabd4bdf708
Solidity
PaymentSplitterUpgradeable
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer { __Context_init_unchained(); __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } uint256[43] private __gap; }
/** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */
NatSpecMultiLine
_addPayee
function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); }
/** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 6200, 6678 ] }
4,795
SuperXinfinitive
SuperXinfinitive.sol
0x996fa957b5a5d83f29008aa0a11c9a209b3a5d8b
Solidity
EIP20Interface
contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line 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); }
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance);
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://20d65a0a03cfc45c20aadf014a2ddeec63574e380c4b38800f4963200fd094f3
{ "func_code_index": [ 638, 716 ] }
4,796
SuperXinfinitive
SuperXinfinitive.sol
0x996fa957b5a5d83f29008aa0a11c9a209b3a5d8b
Solidity
EIP20Interface
contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line 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); }
transfer
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://20d65a0a03cfc45c20aadf014a2ddeec63574e380c4b38800f4963200fd094f3
{ "func_code_index": [ 953, 1035 ] }
4,797
SuperXinfinitive
SuperXinfinitive.sol
0x996fa957b5a5d83f29008aa0a11c9a209b3a5d8b
Solidity
EIP20Interface
contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line 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); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://20d65a0a03cfc45c20aadf014a2ddeec63574e380c4b38800f4963200fd094f3
{ "func_code_index": [ 1358, 1459 ] }
4,798
SuperXinfinitive
SuperXinfinitive.sol
0x996fa957b5a5d83f29008aa0a11c9a209b3a5d8b
Solidity
EIP20Interface
contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line 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); }
approve
function approve(address _spender, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://20d65a0a03cfc45c20aadf014a2ddeec63574e380c4b38800f4963200fd094f3
{ "func_code_index": [ 1749, 1835 ] }
4,799