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
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; }
/** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 3428, 3531 ] }
3,507
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 3982, 4085 ] }
3,508
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } }
/** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 4547, 4758 ] }
3,509
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
div
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } }
/** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 5463, 5673 ] }
3,510
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
/** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 6317, 6527 ] }
3,511
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
isContract
function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; }
/** * @dev 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.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 590, 1017 ] }
3,512
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @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.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 1932, 2334 ] }
3,513
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @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.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 3073, 3251 ] }
3,514
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @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.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 3471, 3671 ] }
3,515
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @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.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 4031, 4262 ] }
3,516
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); }
/** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 4508, 5043 ] }
3,517
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionStaticCall
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 5218, 5422 ] }
3,518
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionStaticCall
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 5604, 6031 ] }
3,519
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionDelegateCall
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 6208, 6413 ] }
3,520
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionDelegateCall
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 6597, 7025 ] }
3,521
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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 virtual returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 450, 542 ] }
3,522
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 1093, 1246 ] }
3,523
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 1393, 1642 ] }
3,524
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
DegenUnitToken
contract DegenUnitToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 private _decimals = 9; // string private _name = "DEGEN UNIT"; string private _symbol = "DEGEN UNIT"; uint256 private _tTotal = 1000 * 10**9 * 10**uint256(_decimals); // uint256 public defaultTaxFee = 0; uint256 public _taxFee = defaultTaxFee; uint256 private _previousTaxFee = _taxFee; // uint256 public defaultMarketingFee = 5; uint256 public _marketingFee = defaultMarketingFee; uint256 private _previousMarketingFee = _marketingFee; uint256 public _marketingFee4Sellers = 5; bool public feesOnSellersAndBuyers = true; uint256 public _maxTxAmount = _tTotal.div(1).div(100); uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100); address payable public marketingWallet = payable(0xF76dc25ffB392C6BaA4163B4EED87d82964C8379); // mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tFeeTotal; uint256 private _rTotal = (MAX - (MAX % _tTotal)); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndSend; bool public SwapAndSendEnabled = true; event SwapAndSendEnabledUpdated(bool enabled); modifier lockTheSwap { inSwapAndSend = true; _; inSwapAndSend = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; } //to recieve ETH receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + send lock? // also, don't get caught in a circular sending event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function setFees(address recipient) private { _taxFee = defaultTaxFee; _marketingFee = defaultMarketingFee; if (recipient == uniswapV2Pair) { // sell _marketingFee = _marketingFee4Sellers; } } function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), contractTokenBalance); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( contractTokenBalance, 0, // accept any amount of ETH path, address(this), block.timestamp ); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { marketingWallet.transfer(contractETHBalance); } } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function setDefaultMarketingFee(uint256 marketingFee) external onlyOwner() { defaultMarketingFee = marketingFee; } function setMarketingFee4Sellers(uint256 marketingFee4Sellers) external onlyOwner() { _marketingFee4Sellers = marketingFee4Sellers; } function setFeesOnSellersAndBuyers(bool _enabled) public onlyOwner() { feesOnSellersAndBuyers = _enabled; } function setSwapAndSendEnabled(bool _enabled) public onlyOwner() { SwapAndSendEnabled = _enabled; emit SwapAndSendEnabledUpdated(_enabled); } function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() { numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing; } function _setMarketingWallet(address payable wallet) external onlyOwner() { marketingWallet = wallet; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } }
// contract implementation
LineComment
//to recieve ETH
LineComment
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 6905, 6939 ] }
3,525
DegenUnitToken
DegenUnitToken.sol
0xa9b78c8b8e6a34d20c75a9864e128bcc83184cfe
Solidity
DegenUnitToken
contract DegenUnitToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 private _decimals = 9; // string private _name = "DEGEN UNIT"; string private _symbol = "DEGEN UNIT"; uint256 private _tTotal = 1000 * 10**9 * 10**uint256(_decimals); // uint256 public defaultTaxFee = 0; uint256 public _taxFee = defaultTaxFee; uint256 private _previousTaxFee = _taxFee; // uint256 public defaultMarketingFee = 5; uint256 public _marketingFee = defaultMarketingFee; uint256 private _previousMarketingFee = _marketingFee; uint256 public _marketingFee4Sellers = 5; bool public feesOnSellersAndBuyers = true; uint256 public _maxTxAmount = _tTotal.div(1).div(100); uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100); address payable public marketingWallet = payable(0xF76dc25ffB392C6BaA4163B4EED87d82964C8379); // mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tFeeTotal; uint256 private _rTotal = (MAX - (MAX % _tTotal)); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndSend; bool public SwapAndSendEnabled = true; event SwapAndSendEnabledUpdated(bool enabled); modifier lockTheSwap { inSwapAndSend = true; _; inSwapAndSend = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; } //to recieve ETH receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + send lock? // also, don't get caught in a circular sending event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function setFees(address recipient) private { _taxFee = defaultTaxFee; _marketingFee = defaultMarketingFee; if (recipient == uniswapV2Pair) { // sell _marketingFee = _marketingFee4Sellers; } } function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), contractTokenBalance); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( contractTokenBalance, 0, // accept any amount of ETH path, address(this), block.timestamp ); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { marketingWallet.transfer(contractETHBalance); } } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function setDefaultMarketingFee(uint256 marketingFee) external onlyOwner() { defaultMarketingFee = marketingFee; } function setMarketingFee4Sellers(uint256 marketingFee4Sellers) external onlyOwner() { _marketingFee4Sellers = marketingFee4Sellers; } function setFeesOnSellersAndBuyers(bool _enabled) public onlyOwner() { feesOnSellersAndBuyers = _enabled; } function setSwapAndSendEnabled(bool _enabled) public onlyOwner() { SwapAndSendEnabled = _enabled; emit SwapAndSendEnabledUpdated(_enabled); } function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() { numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing; } function _setMarketingWallet(address payable wallet) external onlyOwner() { marketingWallet = wallet; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } }
// contract implementation
LineComment
_tokenTransfer
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); }
//this method is responsible for taking all fee, if takeFee is true
LineComment
v0.8.7+commit.e28d00a7
None
ipfs://b9f3ba3a0ddb88a281aaa73b9c4fbf24fd114e6c85f18438083f9c4e21b8e8e6
{ "func_code_index": [ 13022, 13845 ] }
3,526
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
initialize
function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); }
/** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 902, 1282 ] }
3,527
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
/************** * Depositing * **************/
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 1346, 1454 ] }
3,528
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
deposit
function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); }
/** * @dev deposit an amount of the ETH to the caller's balance on L2 */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 1543, 1677 ] }
3,529
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
depositTo
function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); }
/** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 1821, 1975 ] }
3,530
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
_initiateDeposit
function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); }
/** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 2226, 2807 ] }
3,531
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
finalizeWithdrawal
function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); }
/** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 3280, 3541 ] }
3,532
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
_safeTransferETH
function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); }
/** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 3849, 4106 ] }
3,533
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
migrateEth
function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); }
/** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 4348, 4659 ] }
3,534
OVM_L1ETHGateway
contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1ETHGateway.sol
0x40c9067ec8087ecf101fc10d2673636955b81a32
Solidity
OVM_L1ETHGateway
contract OVM_L1ETHGateway is iOVM_L1ETHGateway, OVM_CrossDomainEnabled, Lib_AddressResolver { /******************** * Public Constants * ********************/ uint32 public constant override getFinalizeDepositL2Gas = 1200000; /******************************** * External Contract References * ********************************/ address public ovmEth; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _ovmEth L2 OVM_ETH implementation of iOVM_DepositedToken */ function initialize( address _libAddressManager, address _ovmEth ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); ovmEth = _ovmEth; messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Depositing * **************/ receive() external payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of the ETH to the caller's balance on L2 */ function deposit() external override payable { _initiateDeposit(msg.sender, msg.sender); } /** * @dev deposit an amount of ETH to a recipients's balance on L2 * @param _to L2 address to credit the withdrawal to */ function depositTo( address _to ) external override payable { _initiateDeposit(msg.sender, _to); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit. * * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 */ function _initiateDeposit( address _from, address _to ) internal { // Construct calldata for l2ETHGateway.finalizeDeposit(_to, _amount) bytes memory data = abi.encodeWithSelector( iOVM_L2DepositedToken.finalizeDeposit.selector, _to, msg.value ); // Send calldata into L2 sendCrossDomainMessage( ovmEth, data, getFinalizeDepositL2Gas ); emit DepositInitiated(_from, _to, msg.value); } /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized. * * @param _to L1 address to credit the withdrawal to * @param _amount Amount of the ETH to withdraw */ function finalizeWithdrawal( address _to, uint256 _amount ) external override onlyFromCrossDomainAccount(ovmEth) { _safeTransferETH(_to, _amount); emit WithdrawalFinalized(_to, _amount); } /********************************** * Internal Functions: Accounting * **********************************/ /** * @dev Internal accounting function for moving around L1 ETH. * * @param _to L1 address to transfer ETH to * @param _value Amount of ETH to send to */ function _safeTransferETH( address _to, uint256 _value ) internal { (bool success, ) = _to.call{value: _value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Migrates entire ETH balance to another gateway * @param _to Gateway Proxy address to migrate ETH to */ function migrateEth(address payable _to) external { address owner = Lib_AddressManager(libAddressManager).owner(); require(msg.sender == owner, "Only the owner can migrate ETH"); uint256 balance = address(this).balance; OVM_L1ETHGateway(_to).donateETH{value:balance}(); } /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */ function donateETH() external payable {} }
/** * @title OVM_L1ETHGateway * @dev The L1 ETH Gateway is a contract which stores deposited ETH that is in use on L2. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
donateETH
function donateETH() external payable {}
/** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 4812, 4856 ] }
3,535
SakeVoterCalc
contracts/SakeBar.sol
0x44d84a9da47fd8f4a06ad66b197d1441fca53f92
Solidity
SakeBar
contract SakeBar is ERC20("SakeBar", "xSAKE"){ using SafeMath for uint256; IERC20 public sake; constructor(IERC20 _sake) public { require(address(_sake) != address(0), "invalid address"); sake = _sake; } // Enter the bar. Pay some SAKEs. Earn some shares. function enter(uint256 _amount) public { uint256 totalSake = sake.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalSake == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalSake); _mint(msg.sender, what); } sake.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your SAKEs. function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(sake.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); sake.transfer(msg.sender, what); } }
enter
function enter(uint256 _amount) public { uint256 totalSake = sake.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalSake == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalSake); _mint(msg.sender, what); } sake.transferFrom(msg.sender, address(this), _amount); }
// Enter the bar. Pay some SAKEs. Earn some shares.
LineComment
v0.6.12+commit.27d51765
None
ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20
{ "func_code_index": [ 304, 754 ] }
3,536
SakeVoterCalc
contracts/SakeBar.sol
0x44d84a9da47fd8f4a06ad66b197d1441fca53f92
Solidity
SakeBar
contract SakeBar is ERC20("SakeBar", "xSAKE"){ using SafeMath for uint256; IERC20 public sake; constructor(IERC20 _sake) public { require(address(_sake) != address(0), "invalid address"); sake = _sake; } // Enter the bar. Pay some SAKEs. Earn some shares. function enter(uint256 _amount) public { uint256 totalSake = sake.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalSake == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalSake); _mint(msg.sender, what); } sake.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your SAKEs. function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(sake.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); sake.transfer(msg.sender, what); } }
leave
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(sake.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); sake.transfer(msg.sender, what); }
// Leave the bar. Claim back your SAKEs.
LineComment
v0.6.12+commit.27d51765
None
ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20
{ "func_code_index": [ 803, 1062 ] }
3,537
UBURNSale
UBURNSale.sol
0x1f165586c4c57766971d11e7467dd5ebb153f16b
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; }
/** * @dev Multiplies two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://068e4e9849e8de16f01dd30c034edb4e4f1048bdf05fc41c943cf93b55816cfd
{ "func_code_index": [ 98, 496 ] }
3,538
UBURNSale
UBURNSale.sol
0x1f165586c4c57766971d11e7467dd5ebb153f16b
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://068e4e9849e8de16f01dd30c034edb4e4f1048bdf05fc41c943cf93b55816cfd
{ "func_code_index": [ 618, 902 ] }
3,539
UBURNSale
UBURNSale.sol
0x1f165586c4c57766971d11e7467dd5ebb153f16b
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; }
/** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://068e4e9849e8de16f01dd30c034edb4e4f1048bdf05fc41c943cf93b55816cfd
{ "func_code_index": [ 1027, 1166 ] }
3,540
UBURNSale
UBURNSale.sol
0x1f165586c4c57766971d11e7467dd5ebb153f16b
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
/** * @dev Adds two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://068e4e9849e8de16f01dd30c034edb4e4f1048bdf05fc41c943cf93b55816cfd
{ "func_code_index": [ 1241, 1380 ] }
3,541
UBURNSale
UBURNSale.sol
0x1f165586c4c57766971d11e7467dd5ebb153f16b
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; }
/** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://068e4e9849e8de16f01dd30c034edb4e4f1048bdf05fc41c943cf93b55816cfd
{ "func_code_index": [ 1525, 1642 ] }
3,542
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
initialize
function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); }
/** * @param _libAddressManager Address of the Address Manager. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 1634, 2261 ] }
3,543
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
pause
function pause() external onlyOwner { _pause(); }
/** * Pause relaying. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 2302, 2387 ] }
3,544
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
blockMessage
function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); }
/** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 2494, 2715 ] }
3,545
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
allowMessage
function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); }
/** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 2822, 3044 ] }
3,546
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
relayMessage
function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; }
/** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 3161, 5103 ] }
3,547
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
replayMessage
function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); }
/** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 5231, 5813 ] }
3,548
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
_verifyXDomainMessage
function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); }
/** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 6133, 6477 ] }
3,549
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
_verifyStateRootProof
function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); }
/** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 6672, 7311 ] }
3,550
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
_verifyStorageProof
function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); }
/** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 7566, 8893 ] }
3,551
OVM_L1CrossDomainMessenger
contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol
0x598f2b19e983910529affab7d219724a019339cc
Solidity
OVM_L1CrossDomainMessenger
contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Abs_BaseCrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, _sender, _message, _messageNonce ); require( sentMessages[keccak256(xDomainCalldata)] == true, "Provided message has not already been sent." ); _sendXDomainMessage(xDomainCalldata, _gasLimit); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(0x4200000000000000000000000000000000000000), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); } }
/** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */
NatSpecMultiLine
_sendXDomainMessage
function _sendXDomainMessage( bytes memory _message, uint256 _gasLimit ) override internal { iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")).enqueue( resolve("OVM_L2CrossDomainMessenger"), _gasLimit, _message ); }
/** * Sends a cross domain message. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */
NatSpecMultiLine
v0.7.6+commit.7338295f
MIT
{ "func_code_index": [ 9043, 9381 ] }
3,552
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 94, 154 ] }
3,553
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 237, 310 ] }
3,554
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 534, 616 ] }
3,555
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 895, 983 ] }
3,556
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 1647, 1726 ] }
3,557
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 2039, 2141 ] }
3,558
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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) { 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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 259, 445 ] }
3,559
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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) { 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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 723, 864 ] }
3,560
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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) { 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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 1162, 1359 ] }
3,561
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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) { 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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 1613, 2089 ] }
3,562
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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) { 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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 2560, 2697 ] }
3,563
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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) { 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) { 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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 3188, 3471 ] }
3,564
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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) { 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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 3931, 4066 ] }
3,565
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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) { 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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 4546, 4717 ] }
3,566
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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.6+commit.6c089d02
None
ipfs://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 606, 1230 ] }
3,567
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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.6+commit.6c089d02
None
ipfs://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 2160, 2562 ] }
3,568
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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.6+commit.6c089d02
None
ipfs://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 3318, 3496 ] }
3,569
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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.6+commit.6c089d02
None
ipfs://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 3721, 3922 ] }
3,570
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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.6+commit.6c089d02
None
ipfs://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 4292, 4523 ] }
3,571
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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.6+commit.6c089d02
None
ipfs://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 4774, 5095 ] }
3,572
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
Solidity
SafeERC20
library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
/** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */
NatSpecMultiLine
safeApprove
function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); }
/** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 747, 1374 ] }
3,573
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
Solidity
SafeERC20
library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
/** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */
NatSpecMultiLine
_callOptionalReturn
function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } }
/** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 2393, 3159 ] }
3,574
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 497, 581 ] }
3,575
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 1139, 1292 ] }
3,576
ChadsLiquidityPool
ChadsLiquidityPool.sol
0x294ca5f24e1e9278072e398f607c8e60075ca574
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://122f8e564f8722dd1cdb941da6c885f56b443ecf7e38d556ca7f3778725cc88c
{ "func_code_index": [ 1442, 1691 ] }
3,577
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
// solhint-disable-next-line no-empty-blocks
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3422, 3455 ] }
3,578
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
addUserToMigrate
function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; }
/// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate.
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3849, 4224 ] }
3,579
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
uADPriceReset
function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); }
/// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 4841, 5580 ] }
3,580
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
crvPriceReset
function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); }
/// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5994, 6768 ] }
3,581
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
addProtocolToken
function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); }
/// Collectable Dust
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6982, 7135 ] }
3,582
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
deposit
function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); }
/// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 8251, 9670 ] }
3,583
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
addLiquidity
function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); }
/// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 9945, 12394 ] }
3,584
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
removeLiquidity
function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); }
/// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 12657, 15390 ] }
3,585
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
pendingLpRewards
function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; }
// View function to see pending lpRewards on frontend.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 15451, 16962 ] }
3,586
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
migrate
function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); }
/// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 17214, 17522 ] }
3,587
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
lpRewardForShares
function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } }
/// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 17717, 18050 ] }
3,588
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
_migrate
function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); }
/// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 18578, 19949 ] }
3,589
BondingShareV2
contracts/BondingV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingV2
contract BondingV2 is CollectableDust, Pausable { using SafeERC20 for IERC20; bytes public data = ""; UbiquityAlgorithmicDollarManager public manager; uint256 public constant ONE = uint256(1 ether); // 3Crv has 18 decimals uint256 public bondingDiscountMultiplier = uint256(1000000 gwei); // 0.001 uint256 public blockCountInAWeek = 45361; uint256 public accLpRewardPerShare = 0; uint256 public lpRewards; uint256 public totalLpToMigrate; address public bondingFormulasAddress; address public migrator; // temporary address to handle migration address[] private _toMigrateOriginals; uint256[] private _toMigrateLpBalances; uint256[] private _toMigrateWeeks; // toMigrateId[address] > 0 when address is to migrate, or 0 in all other cases mapping(address => uint256) public toMigrateId; bool public migrating = false; event PriceReset( address _tokenWithdrawn, uint256 _amountWithdrawn, uint256 _amountTransfered ); event Deposit( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount, uint256 _weeks, uint256 _endBlock ); event RemoveLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _lpAmountTransferred, uint256 _lprewards, uint256 _bondingShareAmount ); event AddLiquidityFromBond( address indexed _user, uint256 indexed _id, uint256 _lpAmount, uint256 _bondingShareAmount ); event BondingDiscountMultiplierUpdated(uint256 _bondingDiscountMultiplier); event BlockCountInAWeekUpdated(uint256 _blockCountInAWeek); event Migrated( address indexed _user, uint256 indexed _id, uint256 _lpsAmount, uint256 _sharesAmount, uint256 _weeks ); modifier onlyBondingManager() { require( manager.hasRole(manager.BONDING_MANAGER_ROLE(), msg.sender), "not manager" ); _; } modifier onlyPauser() { require( manager.hasRole(manager.PAUSER_ROLE(), msg.sender), "not pauser" ); _; } modifier onlyMigrator() { require(msg.sender == migrator, "not migrator"); _; } modifier whenMigrating() { require(migrating, "not in migration"); _; } constructor( address _manager, address _bondingFormulasAddress, address[] memory _originals, uint256[] memory _lpBalances, uint256[] memory _weeks ) CollectableDust() Pausable() { manager = UbiquityAlgorithmicDollarManager(_manager); bondingFormulasAddress = _bondingFormulasAddress; migrator = msg.sender; uint256 lgt = _originals.length; require(lgt > 0, "address array empty"); require(lgt == _lpBalances.length, "balances array not same length"); require(lgt == _weeks.length, "weeks array not same length"); _toMigrateOriginals = _originals; _toMigrateLpBalances = _lpBalances; _toMigrateWeeks = _weeks; for (uint256 i = 0; i < lgt; ++i) { toMigrateId[_originals[i]] = i + 1; totalLpToMigrate += _lpBalances[i]; } } // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @dev addUserToMigrate add a user to migrate from V1. /// IMPORTANT execute that function BEFORE sending the corresponding LP token /// otherwise they will have extra LP rewards /// @param _original address of v1 user /// @param _lpBalance LP Balance of v1 user /// @param _weeks weeks lockup of v1 user /// @notice user will then be able to migrate. function addUserToMigrate( address _original, uint256 _lpBalance, uint256 _weeks ) external onlyMigrator { _toMigrateOriginals.push(_original); _toMigrateLpBalances.push(_lpBalance); totalLpToMigrate += _lpBalance; _toMigrateWeeks.push(_weeks); toMigrateId[_original] = _toMigrateOriginals.length; } function setMigrator(address _migrator) external onlyMigrator { migrator = _migrator; } function setMigrating(bool _migrating) external onlyMigrator { migrating = _migrating; } /// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside /// the bonding contract and send the uAD received to the treasury. /// This will have the immediate effect of pushing the uAD price HIGHER /// @param amount of LP token to be removed for uAD /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function uADPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 0, 0 ); ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.dollarTokenAddress()).balanceOf( address(this) ); IERC20(manager.dollarTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.dollarTokenAddress(), coinWithdrawn, toTransfer ); } /// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside /// the bonding contract and send the 3CRV received to the treasury /// This will have the immediate effect of pushing the uAD price LOWER /// @param amount of LP token to be removed for 3CRV tokens /// @notice it will remove one coin only from the curve LP share sitting in the bonding contract function crvPriceReset(uint256 amount) external onlyBondingManager { IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress()); // remove one coin uint256 coinWithdrawn = metaPool.remove_liquidity_one_coin( amount, 1, 0 ); // update twap ITWAPOracle(manager.twapOracleAddress()).update(); uint256 toTransfer = IERC20(manager.curve3PoolTokenAddress()).balanceOf( address(this) ); IERC20(manager.curve3PoolTokenAddress()).transfer( manager.treasuryAddress(), toTransfer ); emit PriceReset( manager.curve3PoolTokenAddress(), coinWithdrawn, toTransfer ); } function setBondingFormulasAddress(address _bondingFormulasAddress) external onlyBondingManager { bondingFormulasAddress = _bondingFormulasAddress; } /// Collectable Dust function addProtocolToken(address _token) external override onlyBondingManager { _addProtocolToken(_token); } function removeProtocolToken(address _token) external override onlyBondingManager { _removeProtocolToken(_token); } function sendDust( address _to, address _token, uint256 _amount ) external override onlyBondingManager { _sendDust(_to, _token, _amount); } function setBondingDiscountMultiplier(uint256 _bondingDiscountMultiplier) external onlyBondingManager { bondingDiscountMultiplier = _bondingDiscountMultiplier; emit BondingDiscountMultiplierUpdated(_bondingDiscountMultiplier); } function setBlockCountInAWeek(uint256 _blockCountInAWeek) external onlyBondingManager { blockCountInAWeek = _blockCountInAWeek; emit BlockCountInAWeekUpdated(_blockCountInAWeek); } /// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares /// @param _lpsAmount of LP token to send /// @param _weeks during lp token will be held /// @notice weeks act as a multiplier for the amount of bonding shares to be received function deposit(uint256 _lpsAmount, uint256 _weeks) external whenNotPaused returns (uint256 _id) { require( 1 <= _weeks && _weeks <= 208, "Bonding: duration must be between 1 and 208 weeks" ); ITWAPOracle(manager.twapOracleAddress()).update(); // update the accumulated lp rewards per shares _updateLpPerShare(); // transfer lp token to the bonding contract IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _lpsAmount ); // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // calculate end locking period block number uint256 _endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(msg.sender, _lpsAmount, _sharesAmount, _endBlock); // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); emit Deposit( msg.sender, _id, _lpsAmount, _sharesAmount, _weeks, _endBlock ); } /// @dev Add an amount of uAD-3CRV LP tokens /// @param _amount of LP token to deposit /// @param _id bonding shares id /// @param _weeks during lp token will be held /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function addLiquidity( uint256 _amount, uint256 _id, uint256 _weeks ) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); // calculate pending LP rewards uint256 sharesToRemove = bs[0]; _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares( sharesToRemove, bond.lpRewardDebt ); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsAddLiquidityNormalization(bond, bs, pendingLpReward); // add these LP Rewards to the deposited amount of LP token bond.lpAmount += pendingLpReward; lpRewards -= pendingLpReward; IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom( msg.sender, address(this), _amount ); bond.lpAmount += _amount; // redeem all shares IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // calculate the amount of share based on the new amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(bond.lpAmount, _weeks, bondingDiscountMultiplier); // deposit new shares IMasterChefV2(manager.masterChefAddress()).deposit( msg.sender, _sharesAmount, _id ); // calculate end locking period block number // 1 week = 45361 blocks = 2371753*7/366 // n = (block + duration * 45361) bond.endBlock = block.number + _weeks * blockCountInAWeek; // should be done after masterchef withdraw _updateLpPerShare(); bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); emit AddLiquidityFromBond( msg.sender, _id, bond.lpAmount, _sharesAmount ); } /// @dev Remove an amount of uAD-3CRV LP tokens /// @param _amount of LP token deposited when _id was created to be withdrawn /// @param _id bonding shares id /// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date function removeLiquidity(uint256 _amount, uint256 _id) external whenNotPaused { ( uint256[2] memory bs, BondingShareV2.Bond memory bond ) = _checkForLiquidity(_id); require(bond.lpAmount >= _amount, "Bonding: amount too big"); // we should decrease the UBQ rewards proportionally to the LP removed // sharesToRemove = (bonding shares * _amount ) / bond.lpAmount ; uint256 sharesToRemove = BondingFormulas(this.bondingFormulasAddress()) .sharesForLP(bond, bs, _amount); //get all its pending LP Rewards _updateLpPerShare(); uint256 pendingLpReward = lpRewardForShares(bs[0], bond.lpRewardDebt); // update bonding shares // bond.shares = bond.shares - sharesToRemove; // get masterchef for uGOV rewards To ensure correct computation // it needs to be done BEFORE updating the bonding share IMasterChefV2(manager.masterChefAddress()).withdraw( msg.sender, sharesToRemove, _id ); // redeem of the extra LP // bonding lp balance - BondingShareV2.totalLP IERC20 metapool = IERC20(manager.stableSwapMetaPoolAddress()); // add an extra step to be able to decrease rewards if locking end is near pendingLpReward = BondingFormulas(this.bondingFormulasAddress()) .lpRewardsRemoveLiquidityNormalization(bond, bs, pendingLpReward); uint256 correctedAmount = BondingFormulas(this.bondingFormulasAddress()) .correctedAmountToWithdraw( BondingShareV2(manager.bondingShareAddress()).totalLP(), metapool.balanceOf(address(this)) - lpRewards, _amount ); lpRewards -= pendingLpReward; bond.lpAmount -= _amount; // bond.lpRewardDebt = (bonding shares * accLpRewardPerShare) / 1e18; // user.amount.mul(pool.accSushiPerShare).div(1e12); // should be done after masterchef withdraw bond.lpRewardDebt = (IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id )[0] * accLpRewardPerShare) / 1e12; BondingShareV2(manager.bondingShareAddress()).updateBond( _id, bond.lpAmount, bond.lpRewardDebt, bond.endBlock ); // lastly redeem lp tokens metapool.safeTransfer(msg.sender, correctedAmount + pendingLpReward); emit RemoveLiquidityFromBond( msg.sender, _id, _amount, correctedAmount, pendingLpReward, sharesToRemove ); } // View function to see pending lpRewards on frontend. function pendingLpRewards(uint256 _id) external view returns (uint256) { BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); BondingShareV2.Bond memory bond = bonding.getBond(_id); uint256[2] memory bs = IMasterChefV2(manager.masterChefAddress()) .getBondingShareInfo(_id); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance minus the total deposited LP if (lpBalance >= (bonding.totalLP() + totalLpToMigrate)) { uint256 currentLpRewards = lpBalance - (bonding.totalLP() + totalLpToMigrate); uint256 curAccLpRewardPerShare = accLpRewardPerShare; // if new rewards we should calculate the new curAccLpRewardPerShare if (currentLpRewards > lpRewards) { uint256 newLpRewards = currentLpRewards - lpRewards; curAccLpRewardPerShare = accLpRewardPerShare + ((newLpRewards * 1e12) / IMasterChefV2(manager.masterChefAddress()) .totalShares()); } // we multiply the shares amount by the accumulated lpRewards per share // and remove the lp Reward Debt return (bs[0] * (curAccLpRewardPerShare)) / (1e12) - (bond.lpRewardDebt); } return 0; } function pause() public virtual onlyPauser { _pause(); } function unpause() public virtual onlyPauser { _unpause(); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function migrate() public whenMigrating returns (uint256 _id) { _id = toMigrateId[msg.sender]; require(_id > 0, "not v1 address"); _migrate( _toMigrateOriginals[_id - 1], _toMigrateLpBalances[_id - 1], _toMigrateWeeks[_id - 1] ); } /// @dev return the amount of Lp token rewards an amount of shares entitled /// @param amount of bonding shares /// @param lpRewardDebt lp rewards that has already been distributed function lpRewardForShares(uint256 amount, uint256 lpRewardDebt) public view returns (uint256 pendingLpReward) { if (accLpRewardPerShare > 0) { pendingLpReward = (amount * accLpRewardPerShare) / 1e12 - (lpRewardDebt); } } function currentShareValue() public view returns (uint256 priceShare) { uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); // priceShare = totalLP / totalShares priceShare = IUbiquityFormulas(manager.formulasAddress()).bondPrice( BondingShareV2(manager.bondingShareAddress()).totalLP(), totalShares, ONE ); } /// @dev migrate let a user migrate from V1 /// @notice user will then be able to migrate function _migrate( address user, uint256 _lpsAmount, uint256 _weeks ) internal returns (uint256 _id) { require(toMigrateId[user] > 0, "not v1 address"); require(_lpsAmount > 0, "LP amount is zero"); require( 1 <= _weeks && _weeks <= 208, "Duration must be between 1 and 208 weeks" ); // unregister address toMigrateId[user] = 0; // calculate the amount of share based on the amount of lp deposited and the duration uint256 _sharesAmount = IUbiquityFormulas(manager.formulasAddress()) .durationMultiply(_lpsAmount, _weeks, bondingDiscountMultiplier); // update the accumulated lp rewards per shares _updateLpPerShare(); // calculate end locking period block number uint256 endBlock = block.number + _weeks * blockCountInAWeek; _id = _mint(user, _lpsAmount, _sharesAmount, endBlock); // reduce the total LP to migrate after the minting // to keep the _updateLpPerShare calculation consistent totalLpToMigrate -= _lpsAmount; // set masterchef for uGOV rewards IMasterChefV2(manager.masterChefAddress()).deposit( user, _sharesAmount, _id ); emit Migrated(user, _id, _lpsAmount, _sharesAmount, _weeks); } /// @dev update the accumulated excess LP per share function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } } function _mint( address to, uint256 lpAmount, uint256 shares, uint256 endBlock ) internal returns (uint256) { uint256 _currentShareValue = currentShareValue(); require( _currentShareValue != 0, "Bonding: share value should not be null" ); // set the lp rewards debts so that this bonding share only get lp rewards from this day uint256 lpRewardDebt = (shares * accLpRewardPerShare) / 1e12; return BondingShareV2(manager.bondingShareAddress()).mint( to, lpAmount, lpRewardDebt, endBlock ); } function _checkForLiquidity(uint256 _id) internal returns (uint256[2] memory bs, BondingShareV2.Bond memory bond) { require( IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf( msg.sender, _id ) == 1, "Bonding: caller is not owner" ); BondingShareV2 bonding = BondingShareV2(manager.bondingShareAddress()); bond = bonding.getBond(_id); require( block.number > bond.endBlock, "Bonding: Redeem not allowed before bonding time" ); ITWAPOracle(manager.twapOracleAddress()).update(); bs = IMasterChefV2(manager.masterChefAddress()).getBondingShareInfo( _id ); } }
_updateLpPerShare
function _updateLpPerShare() internal { BondingShareV2 bond = BondingShareV2(manager.bondingShareAddress()); uint256 lpBalance = IERC20(manager.stableSwapMetaPoolAddress()) .balanceOf(address(this)); // the excess LP is the current balance // minus the total deposited LP + LP that needs to be migrated uint256 totalShares = IMasterChefV2(manager.masterChefAddress()) .totalShares(); if ( lpBalance >= (bond.totalLP() + totalLpToMigrate) && totalShares > 0 ) { uint256 currentLpRewards = lpBalance - (bond.totalLP() + totalLpToMigrate); // is there new LP rewards to be distributed ? if (currentLpRewards > lpRewards) { // we calculate the new accumulated LP rewards per share accLpRewardPerShare = accLpRewardPerShare + (((currentLpRewards - lpRewards) * 1e12) / totalShares); // update the bonding contract lpRewards lpRewards = currentLpRewards; } } }
/// @dev update the accumulated excess LP per share
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 20007, 21139 ] }
3,590
XI
XI.sol
0x51909adff69f3b82cffbaf93ed668566764ca233
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://2358acac06dd1bd3eb423be2fab1e488a0c544c83d57b2621589a2c03d205774
{ "func_code_index": [ 95, 302 ] }
3,591
XI
XI.sol
0x51909adff69f3b82cffbaf93ed668566764ca233
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://2358acac06dd1bd3eb423be2fab1e488a0c544c83d57b2621589a2c03d205774
{ "func_code_index": [ 392, 692 ] }
3,592
XI
XI.sol
0x51909adff69f3b82cffbaf93ed668566764ca233
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://2358acac06dd1bd3eb423be2fab1e488a0c544c83d57b2621589a2c03d205774
{ "func_code_index": [ 812, 940 ] }
3,593
XI
XI.sol
0x51909adff69f3b82cffbaf93ed668566764ca233
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://2358acac06dd1bd3eb423be2fab1e488a0c544c83d57b2621589a2c03d205774
{ "func_code_index": [ 1010, 1156 ] }
3,594
DssSpell
DssSpell.sol
0xd155716c72edcd14ffb60131f83b3ef4d34aa201
Solidity
DssSpell
contract DssSpell { DSPauseAbstract public pause = DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3); address public action; bytes32 public tag; uint256 public eta; bytes public sig; uint256 public expiration; bool public done; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/15215ebaf8bbb4a20567b3233383788a68afb58b/governance/votes/Executive%20vote%20-%20September%2014%2C%202020.md -q -O - 2>/dev/null)" string constant public description = "2020-09-14 MakerDAO Executive Spell | Hash: 0xf0155120204be06c56616181ea82bbfa93f48494455c6d0b3c0ab1d581464657"; constructor() public { sig = abi.encodeWithSignature("execute()"); action = address(new SpellAction()); bytes32 _tag; address _action = action; assembly { _tag := extcodehash(_action) } tag = _tag; expiration = now + 30 days; } // modifier officeHours { // uint day = (now / 1 days + 3) % 7; // require(day < 5, "Can only be cast on a weekday"); // uint hour = now / 1 hours % 24; // require(hour >= 14 && hour < 21, "Outside office hours"); // _; // } function schedule() public { require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + DSPauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); } function cast() public /*officeHours*/ { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } }
schedule
function schedule() public { require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + DSPauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); }
// modifier officeHours { // uint day = (now / 1 days + 3) % 7; // require(day < 5, "Can only be cast on a weekday"); // uint hour = now / 1 hours % 24; // require(hour >= 14 && hour < 21, "Outside office hours"); // _; // }
LineComment
v0.5.12+commit.7709ece9
Unknown
bzzr://0e6287828387b71b1fb5f7eb80a06b6c4287498cdb2c47889a51e736d460f9c3
{ "func_code_index": [ 1441, 1713 ] }
3,595
BurnBase
BurnBase.sol
0x3ad1ed0ac57533d228c0c1971ea6749d98dea815
Solidity
BurnBase
contract BurnBase is ERC20Detailed { using SafeMath for uint256; ERC20Detailed internal WETH = ERC20Detailed(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BurnBase"; string constant tokenSymbol = "BurnBase"; uint8 constant tokenDecimals = 18; uint256 constant easyDecimals = 1000000000000000000; // yes you can use an exponent instead if you want uint256 _totalSupply = 5000 * easyDecimals; //any tokens sent here ? IERC20 currentToken ; address payable public _owner; address public _pairAddress; //modifiers modifier onlyOwner() { require(msg.sender == _owner); _; } constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _owner = msg.sender; //temporarily until the proper pair address is set. To prevent errors if transfer occurs prior to setting pair address. _pairAddress = msg.sender; require(_totalSupply != 0); //create initialSupply _balances[_owner] = _balances[_owner].add(_totalSupply); emit Transfer(address(0), _owner, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } //0% uint256 public basePercentage = 1000; function findPercentage(uint256 amount) public view returns (uint256) { uint256 percent = amount.mul(basePercentage).div(10000); return percent; } //turns burn on/off called by owner only function burnOnOff() external onlyOwner { if(basePercentage == 0) basePercentage = 1000; else basePercentage = 0; } //burn function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } //no zeros for decimals necessary function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } //_pairAddress function setPairAddress() external onlyOwner { _pairAddress = uniswapFactory.getPair(address(WETH), address(this)); } //take back unclaimed tokens function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } // transfer function _executeTransfer(address _from, address _to, uint256 _value) private { if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); // Check if the sender has enough if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows //burn if selling only. do not burn if owner adds/removes Liquidity if(_to != _pairAddress || _from == _owner || _to == _owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); // Subtract from the sender _balances[_to] = SafeMath.add(_balances[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place }//if else //selling { //limit on sell //if(_value > 25 * easyDecimals) revert("25 token sell limit exceeded"); //sell limit uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); // Subtract from the sender _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); // Notify anyone listening that this transfer took place //anything to burn? burn it if(tokensToBurn > 0) _burn(_from, tokensToBurn); }//else }//_executeTransfer }
burnOnOff
function burnOnOff() external onlyOwner { if(basePercentage == 0) basePercentage = 1000; else basePercentage = 0;
//turns burn on/off called by owner only
LineComment
v0.5.17+commit.d19bba13
None
bzzr://a0235a3da77c791ed26ee9d71cb3768db376a71927b29f1fe133e7a269f4f89b
{ "func_code_index": [ 2782, 2941 ] }
3,596
BurnBase
BurnBase.sol
0x3ad1ed0ac57533d228c0c1971ea6749d98dea815
Solidity
BurnBase
contract BurnBase is ERC20Detailed { using SafeMath for uint256; ERC20Detailed internal WETH = ERC20Detailed(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BurnBase"; string constant tokenSymbol = "BurnBase"; uint8 constant tokenDecimals = 18; uint256 constant easyDecimals = 1000000000000000000; // yes you can use an exponent instead if you want uint256 _totalSupply = 5000 * easyDecimals; //any tokens sent here ? IERC20 currentToken ; address payable public _owner; address public _pairAddress; //modifiers modifier onlyOwner() { require(msg.sender == _owner); _; } constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _owner = msg.sender; //temporarily until the proper pair address is set. To prevent errors if transfer occurs prior to setting pair address. _pairAddress = msg.sender; require(_totalSupply != 0); //create initialSupply _balances[_owner] = _balances[_owner].add(_totalSupply); emit Transfer(address(0), _owner, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } //0% uint256 public basePercentage = 1000; function findPercentage(uint256 amount) public view returns (uint256) { uint256 percent = amount.mul(basePercentage).div(10000); return percent; } //turns burn on/off called by owner only function burnOnOff() external onlyOwner { if(basePercentage == 0) basePercentage = 1000; else basePercentage = 0; } //burn function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } //no zeros for decimals necessary function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } //_pairAddress function setPairAddress() external onlyOwner { _pairAddress = uniswapFactory.getPair(address(WETH), address(this)); } //take back unclaimed tokens function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } // transfer function _executeTransfer(address _from, address _to, uint256 _value) private { if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); // Check if the sender has enough if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows //burn if selling only. do not burn if owner adds/removes Liquidity if(_to != _pairAddress || _from == _owner || _to == _owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); // Subtract from the sender _balances[_to] = SafeMath.add(_balances[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place }//if else //selling { //limit on sell //if(_value > 25 * easyDecimals) revert("25 token sell limit exceeded"); //sell limit uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); // Subtract from the sender _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); // Notify anyone listening that this transfer took place //anything to burn? burn it if(tokensToBurn > 0) _burn(_from, tokensToBurn); }//else }//_executeTransfer }
burn
function burn(uint256 amount) external { _burn(msg.sender, amount); }
//burn
LineComment
v0.5.17+commit.d19bba13
None
bzzr://a0235a3da77c791ed26ee9d71cb3768db376a71927b29f1fe133e7a269f4f89b
{ "func_code_index": [ 2962, 3062 ] }
3,597
BurnBase
BurnBase.sol
0x3ad1ed0ac57533d228c0c1971ea6749d98dea815
Solidity
BurnBase
contract BurnBase is ERC20Detailed { using SafeMath for uint256; ERC20Detailed internal WETH = ERC20Detailed(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BurnBase"; string constant tokenSymbol = "BurnBase"; uint8 constant tokenDecimals = 18; uint256 constant easyDecimals = 1000000000000000000; // yes you can use an exponent instead if you want uint256 _totalSupply = 5000 * easyDecimals; //any tokens sent here ? IERC20 currentToken ; address payable public _owner; address public _pairAddress; //modifiers modifier onlyOwner() { require(msg.sender == _owner); _; } constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _owner = msg.sender; //temporarily until the proper pair address is set. To prevent errors if transfer occurs prior to setting pair address. _pairAddress = msg.sender; require(_totalSupply != 0); //create initialSupply _balances[_owner] = _balances[_owner].add(_totalSupply); emit Transfer(address(0), _owner, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } //0% uint256 public basePercentage = 1000; function findPercentage(uint256 amount) public view returns (uint256) { uint256 percent = amount.mul(basePercentage).div(10000); return percent; } //turns burn on/off called by owner only function burnOnOff() external onlyOwner { if(basePercentage == 0) basePercentage = 1000; else basePercentage = 0; } //burn function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } //no zeros for decimals necessary function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } //_pairAddress function setPairAddress() external onlyOwner { _pairAddress = uniswapFactory.getPair(address(WETH), address(this)); } //take back unclaimed tokens function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } // transfer function _executeTransfer(address _from, address _to, uint256 _value) private { if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); // Check if the sender has enough if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows //burn if selling only. do not burn if owner adds/removes Liquidity if(_to != _pairAddress || _from == _owner || _to == _owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); // Subtract from the sender _balances[_to] = SafeMath.add(_balances[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place }//if else //selling { //limit on sell //if(_value > 25 * easyDecimals) revert("25 token sell limit exceeded"); //sell limit uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); // Subtract from the sender _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); // Notify anyone listening that this transfer took place //anything to burn? burn it if(tokensToBurn > 0) _burn(_from, tokensToBurn); }//else }//_executeTransfer }
multiTransferEqualAmount
function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } }
//no zeros for decimals necessary
LineComment
v0.5.17+commit.d19bba13
None
bzzr://a0235a3da77c791ed26ee9d71cb3768db376a71927b29f1fe133e7a269f4f89b
{ "func_code_index": [ 3486, 3765 ] }
3,598
BurnBase
BurnBase.sol
0x3ad1ed0ac57533d228c0c1971ea6749d98dea815
Solidity
BurnBase
contract BurnBase is ERC20Detailed { using SafeMath for uint256; ERC20Detailed internal WETH = ERC20Detailed(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BurnBase"; string constant tokenSymbol = "BurnBase"; uint8 constant tokenDecimals = 18; uint256 constant easyDecimals = 1000000000000000000; // yes you can use an exponent instead if you want uint256 _totalSupply = 5000 * easyDecimals; //any tokens sent here ? IERC20 currentToken ; address payable public _owner; address public _pairAddress; //modifiers modifier onlyOwner() { require(msg.sender == _owner); _; } constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _owner = msg.sender; //temporarily until the proper pair address is set. To prevent errors if transfer occurs prior to setting pair address. _pairAddress = msg.sender; require(_totalSupply != 0); //create initialSupply _balances[_owner] = _balances[_owner].add(_totalSupply); emit Transfer(address(0), _owner, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } //0% uint256 public basePercentage = 1000; function findPercentage(uint256 amount) public view returns (uint256) { uint256 percent = amount.mul(basePercentage).div(10000); return percent; } //turns burn on/off called by owner only function burnOnOff() external onlyOwner { if(basePercentage == 0) basePercentage = 1000; else basePercentage = 0; } //burn function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } //no zeros for decimals necessary function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } //_pairAddress function setPairAddress() external onlyOwner { _pairAddress = uniswapFactory.getPair(address(WETH), address(this)); } //take back unclaimed tokens function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } // transfer function _executeTransfer(address _from, address _to, uint256 _value) private { if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); // Check if the sender has enough if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows //burn if selling only. do not burn if owner adds/removes Liquidity if(_to != _pairAddress || _from == _owner || _to == _owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); // Subtract from the sender _balances[_to] = SafeMath.add(_balances[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place }//if else //selling { //limit on sell //if(_value > 25 * easyDecimals) revert("25 token sell limit exceeded"); //sell limit uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); // Subtract from the sender _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); // Notify anyone listening that this transfer took place //anything to burn? burn it if(tokensToBurn > 0) _burn(_from, tokensToBurn); }//else }//_executeTransfer }
setPairAddress
function setPairAddress() external onlyOwner { _pairAddress = uniswapFactory.getPair(address(WETH), address(this)); }
//_pairAddress
LineComment
v0.5.17+commit.d19bba13
None
bzzr://a0235a3da77c791ed26ee9d71cb3768db376a71927b29f1fe133e7a269f4f89b
{ "func_code_index": [ 4688, 4830 ] }
3,599
BurnBase
BurnBase.sol
0x3ad1ed0ac57533d228c0c1971ea6749d98dea815
Solidity
BurnBase
contract BurnBase is ERC20Detailed { using SafeMath for uint256; ERC20Detailed internal WETH = ERC20Detailed(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BurnBase"; string constant tokenSymbol = "BurnBase"; uint8 constant tokenDecimals = 18; uint256 constant easyDecimals = 1000000000000000000; // yes you can use an exponent instead if you want uint256 _totalSupply = 5000 * easyDecimals; //any tokens sent here ? IERC20 currentToken ; address payable public _owner; address public _pairAddress; //modifiers modifier onlyOwner() { require(msg.sender == _owner); _; } constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _owner = msg.sender; //temporarily until the proper pair address is set. To prevent errors if transfer occurs prior to setting pair address. _pairAddress = msg.sender; require(_totalSupply != 0); //create initialSupply _balances[_owner] = _balances[_owner].add(_totalSupply); emit Transfer(address(0), _owner, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } //0% uint256 public basePercentage = 1000; function findPercentage(uint256 amount) public view returns (uint256) { uint256 percent = amount.mul(basePercentage).div(10000); return percent; } //turns burn on/off called by owner only function burnOnOff() external onlyOwner { if(basePercentage == 0) basePercentage = 1000; else basePercentage = 0; } //burn function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } //no zeros for decimals necessary function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } //_pairAddress function setPairAddress() external onlyOwner { _pairAddress = uniswapFactory.getPair(address(WETH), address(this)); } //take back unclaimed tokens function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } // transfer function _executeTransfer(address _from, address _to, uint256 _value) private { if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); // Check if the sender has enough if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows //burn if selling only. do not burn if owner adds/removes Liquidity if(_to != _pairAddress || _from == _owner || _to == _owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); // Subtract from the sender _balances[_to] = SafeMath.add(_balances[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place }//if else //selling { //limit on sell //if(_value > 25 * easyDecimals) revert("25 token sell limit exceeded"); //sell limit uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); // Subtract from the sender _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); // Notify anyone listening that this transfer took place //anything to burn? burn it if(tokensToBurn > 0) _burn(_from, tokensToBurn); }//else }//_executeTransfer }
withdrawUnclaimedTokens
function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); }
//take back unclaimed tokens
LineComment
v0.5.17+commit.d19bba13
None
bzzr://a0235a3da77c791ed26ee9d71cb3768db376a71927b29f1fe133e7a269f4f89b
{ "func_code_index": [ 4878, 5146 ] }
3,600
BurnBase
BurnBase.sol
0x3ad1ed0ac57533d228c0c1971ea6749d98dea815
Solidity
BurnBase
contract BurnBase is ERC20Detailed { using SafeMath for uint256; ERC20Detailed internal WETH = ERC20Detailed(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "BurnBase"; string constant tokenSymbol = "BurnBase"; uint8 constant tokenDecimals = 18; uint256 constant easyDecimals = 1000000000000000000; // yes you can use an exponent instead if you want uint256 _totalSupply = 5000 * easyDecimals; //any tokens sent here ? IERC20 currentToken ; address payable public _owner; address public _pairAddress; //modifiers modifier onlyOwner() { require(msg.sender == _owner); _; } constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _owner = msg.sender; //temporarily until the proper pair address is set. To prevent errors if transfer occurs prior to setting pair address. _pairAddress = msg.sender; require(_totalSupply != 0); //create initialSupply _balances[_owner] = _balances[_owner].add(_totalSupply); emit Transfer(address(0), _owner, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } //0% uint256 public basePercentage = 1000; function findPercentage(uint256 amount) public view returns (uint256) { uint256 percent = amount.mul(basePercentage).div(10000); return percent; } //turns burn on/off called by owner only function burnOnOff() external onlyOwner { if(basePercentage == 0) basePercentage = 1000; else basePercentage = 0; } //burn function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } //no zeros for decimals necessary function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**uint256(tokenDecimals); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } //_pairAddress function setPairAddress() external onlyOwner { _pairAddress = uniswapFactory.getPair(address(WETH), address(this)); } //take back unclaimed tokens function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } // transfer function _executeTransfer(address _from, address _to, uint256 _value) private { if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); // Check if the sender has enough if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows //burn if selling only. do not burn if owner adds/removes Liquidity if(_to != _pairAddress || _from == _owner || _to == _owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); // Subtract from the sender _balances[_to] = SafeMath.add(_balances[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place }//if else //selling { //limit on sell //if(_value > 25 * easyDecimals) revert("25 token sell limit exceeded"); //sell limit uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); // Subtract from the sender _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); // Notify anyone listening that this transfer took place //anything to burn? burn it if(tokensToBurn > 0) _burn(_from, tokensToBurn); }//else }//_executeTransfer }
_executeTransfer
function _executeTransfer(address _from, address _to, uint256 _value) private { if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); // Check if the sender has enough if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows //burn if selling only. do not burn if owner adds/removes Liquidity if(_to != _pairAddress || _from == _owner || _to == _owner) { _balances[_from] = SafeMath.sub(_balances[_from], _value); // Subtract from the sender _balances[_to] = SafeMath.add(_balances[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place }//if else //selling { //limit on sell //if(_value > 25 * easyDecimals) revert("25 token sell limit exceeded"); //sell limit uint256 tokensToBurn = findPercentage(_value); uint256 tokensToTransfer = _value.sub(tokensToBurn); _balances[_from] = SafeMath.sub(_balances[_from], tokensToTransfer); // Subtract from the sender _balances[_to] = _balances[_to].add(tokensToTransfer); emit Transfer(_from, _to, tokensToTransfer); // Notify anyone listening that this transfer took place //anything to burn? burn it if(tokensToBurn > 0) _burn(_from, tokensToBurn); }//else }//_executeTransfer
// transfer
LineComment
v0.5.17+commit.d19bba13
None
bzzr://a0235a3da77c791ed26ee9d71cb3768db376a71927b29f1fe133e7a269f4f89b
{ "func_code_index": [ 5188, 7067 ] }
3,601
FSK
FSK.sol
0xfc1078a7bb4521881663df4148434acd991af14c
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
MIT
bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b
{ "func_code_index": [ 673, 870 ] }
3,602
FSK
FSK.sol
0xfc1078a7bb4521881663df4148434acd991af14c
Solidity
BasicToken
contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balanceOf(msg.sender)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balanceOf(msg.sender)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
MIT
bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b
{ "func_code_index": [ 293, 722 ] }
3,603
FSK
FSK.sol
0xfc1078a7bb4521881663df4148434acd991af14c
Solidity
BasicToken
contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balanceOf(msg.sender)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
MIT
bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b
{ "func_code_index": [ 939, 1059 ] }
3,604
FSK
FSK.sol
0xfc1078a7bb4521881663df4148434acd991af14c
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(allowed[_from][msg.sender] >= _value); require(balanceOf(_from) >= _value); require(balances[_to].add(_value) > balances[_to]); // Check for overflows balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(allowed[_from][msg.sender] >= _value); require(balanceOf(_from) >= _value); require(balances[_to].add(_value) > balances[_to]); // Check for overflows balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
MIT
bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b
{ "func_code_index": [ 399, 975 ] }
3,605
FSK
FSK.sol
0xfc1078a7bb4521881663df4148434acd991af14c
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(allowed[_from][msg.sender] >= _value); require(balanceOf(_from) >= _value); require(balances[_to].add(_value) > balances[_to]); // Check for overflows balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.5.11+commit.c082d0b4
MIT
bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b
{ "func_code_index": [ 1217, 1809 ] }
3,606