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
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 239, 409 ] }
4,907
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 667, 800 ] }
4,908
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 1078, 1279 ] }
4,909
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 1513, 1947 ] }
4,910
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 2394, 2523 ] }
4,911
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 2990, 3273 ] }
4,912
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 3709, 3836 ] }
4,913
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 4292, 4471 ] }
4,914
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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); } } } }
isContract
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
/** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 572, 1172 ] }
4,915
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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); } } } }
sendValue
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require( success, "Address: unable to send value, recipient may have reverted" ); }
/** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 2070, 2473 ] }
4,916
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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); } } } }
functionCall
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
/** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 3193, 3378 ] }
4,917
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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); } } } }
functionCall
function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 3591, 3804 ] }
4,918
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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); } } } }
functionCallWithValue
function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 4152, 4447 ] }
4,919
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
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); } } } }
functionCallWithValue
function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); }
/** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 4686, 5041 ] }
4,920
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 544, 620 ] }
4,921
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 1146, 1287 ] }
4,922
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
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.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 1429, 1662 ] }
4,923
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
lock
function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); }
//Locks the contract for owner for the amount of time provided
LineComment
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 1820, 2019 ] }
4,924
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
unlock
function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; }
//Unlocks the contract for owner when _lockTime is exceeds
LineComment
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 2084, 2382 ] }
4,925
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
Solidity
HODLCapital
contract HODLCapital is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; 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 _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "HODLCapital"; string private _symbol = "HODL"; uint8 private _decimals = 9; uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _HODLWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 100000000000000e9; // We will set a minimum amount of tokens to be swaped => 4M uint256 private _numOfTokensToExchangeForTeam = 4 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap() { inSwap = true; _; inSwap = false; } constructor( address payable HODLWalletAddress, address payable marketingWalletAddress ) public { _HODLWalletAddress = HODLWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // UniswapV2 for Ethereum network // 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 isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } 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 excludeAccount(address account) external 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 includeAccount(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 removeAllFee() private { if (_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } 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 sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (sender != owner() && recipient != 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? // also, don't get caught in a circular team event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if ( !inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair ) { // We need to swap the current tokens to ETH and send to the team wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { takeFee = false; } //transfer amount, it will take tax and team fee _tokenTransfer(sender, recipient, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) 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), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _HODLWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } 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 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam ) = _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); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues( tAmount, _taxFee, _teamFee ); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, currentRate ); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 taxFee, uint256 teamFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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 _getTaxFee() private view returns (uint256) { return _taxFee; } function _getMaxTxAmount() private view returns (uint256) { return _maxTxAmount; } function _getETHBalance() public view returns (uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner { require(taxFee >= 1 && taxFee <= 25, "taxFee should be in 1 - 25"); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner { require(teamFee >= 1 && teamFee <= 25, "teamFee should be in 1 - 25"); _teamFee = teamFee; } function _setHODLWallet(address payable HODLWalletAddress) external onlyOwner { _HODLWalletAddress = HODLWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner { require( maxTxAmount >= 100000000000000e9, "maxTxAmount should be greater than 100000000000000e9" ); _maxTxAmount = maxTxAmount; } }
// Contract implementation
LineComment
manualSwap
function manualSwap() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); }
// We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much
LineComment
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 10108, 10255 ] }
4,926
HODLCapital
HODLCapital.sol
0xeda47e13fd1192e32226753dc2261c4a14908fb7
Solidity
HODLCapital
contract HODLCapital is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; 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 _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "HODLCapital"; string private _symbol = "HODL"; uint8 private _decimals = 9; uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _HODLWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 100000000000000e9; // We will set a minimum amount of tokens to be swaped => 4M uint256 private _numOfTokensToExchangeForTeam = 4 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap() { inSwap = true; _; inSwap = false; } constructor( address payable HODLWalletAddress, address payable marketingWalletAddress ) public { _HODLWalletAddress = HODLWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // UniswapV2 for Ethereum network // 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 isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } 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 excludeAccount(address account) external 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 includeAccount(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 removeAllFee() private { if (_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } 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 sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (sender != owner() && recipient != 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? // also, don't get caught in a circular team event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if ( !inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair ) { // We need to swap the current tokens to ETH and send to the team wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { takeFee = false; } //transfer amount, it will take tax and team fee _tokenTransfer(sender, recipient, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) 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), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _HODLWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } 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 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _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 tTeam ) = _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); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues( tAmount, _taxFee, _teamFee ); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, currentRate ); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 taxFee, uint256 teamFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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 _getTaxFee() private view returns (uint256) { return _taxFee; } function _getMaxTxAmount() private view returns (uint256) { return _maxTxAmount; } function _getETHBalance() public view returns (uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner { require(taxFee >= 1 && taxFee <= 25, "taxFee should be in 1 - 25"); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner { require(teamFee >= 1 && teamFee <= 25, "teamFee should be in 1 - 25"); _teamFee = teamFee; } function _setHODLWallet(address payable HODLWalletAddress) external onlyOwner { _HODLWalletAddress = HODLWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner { require( maxTxAmount >= 100000000000000e9, "maxTxAmount should be greater than 100000000000000e9" ); _maxTxAmount = maxTxAmount; } }
// Contract implementation
LineComment
//to recieve ETH from uniswapV2Router when swaping
LineComment
v0.6.12+commit.27d51765
None
ipfs://9c2c7f9cafd0a7530d7a2a99d205ad7b42212cfac9a168d801b0469c70ebe7dd
{ "func_code_index": [ 14165, 14197 ] }
4,927
Fractal
Fractal.sol
0xc9652efc267982b82df4ffd4bba5e0e7392f51f5
Solidity
Fractal
contract Fractal { struct Inversor { address inversor; uint Dia_de_la_inversion; uint Inversion_en_ETH; bool Esta_Activo; } // Fractal Founds Wallet (ETH) by default address owner = 0x78c25AA14b12fa53efDB77a5a46A59e0c571d0A6; address payable FRACTALFOUNDS = 0x78c25AA14b12fa53efDB77a5a46A59e0c571d0A6; //by default // (1st) function Invertir_Ahora() external payable { require(msg.value > 0); uint investment = msg.value; Buscar_Inversor[msg.sender] = Inversor({ inversor: msg.sender, Dia_de_la_inversion: block.timestamp, Inversion_en_ETH: investment, Esta_Activo: true }); FRACTALFOUNDS.transfer(msg.value); } // (2nd) mapping (address => Inversor) public Buscar_Inversor; // (3rd) function Realizar_Pago(address payable _client) external payable { require(msg.value > 0); _client.transfer(msg.value); Buscar_Inversor[_client].Esta_Activo = false; } // (4th) function Cambiar_Direccion_de_Fractal_Founds (address payable _direccion) external { require (msg.sender == owner); FRACTALFOUNDS = _direccion; } }
// SmartContract for Fractal Company - All Rights Reserved // :::::::::: ::::::::: ::: :::::::: ::::::::::: ::: ::: // :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: // +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ // :#::+::# +#++:++#: +#++:++#++: +#+ +#+ +#++:++#++: +#+ // +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ // #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# // ### ### ### ### ### ######## ### ### ### ##########
LineComment
Invertir_Ahora
function Invertir_Ahora() external payable { require(msg.value > 0); uint investment = msg.value; Buscar_Inversor[msg.sender] = Inversor({ inversor: msg.sender, Dia_de_la_inversion: block.timestamp, Inversion_en_ETH: investment, Esta_Activo: true }); FRACTALFOUNDS.transfer(msg.value); }
//by default // (1st)
LineComment
v0.5.16+commit.9c3226ce
None
bzzr://7bb013355a608e8e376975a14c9666d4fc73b86a3416b76bb37a93e39da81ac4
{ "func_code_index": [ 409, 823 ] }
4,928
Fractal
Fractal.sol
0xc9652efc267982b82df4ffd4bba5e0e7392f51f5
Solidity
Fractal
contract Fractal { struct Inversor { address inversor; uint Dia_de_la_inversion; uint Inversion_en_ETH; bool Esta_Activo; } // Fractal Founds Wallet (ETH) by default address owner = 0x78c25AA14b12fa53efDB77a5a46A59e0c571d0A6; address payable FRACTALFOUNDS = 0x78c25AA14b12fa53efDB77a5a46A59e0c571d0A6; //by default // (1st) function Invertir_Ahora() external payable { require(msg.value > 0); uint investment = msg.value; Buscar_Inversor[msg.sender] = Inversor({ inversor: msg.sender, Dia_de_la_inversion: block.timestamp, Inversion_en_ETH: investment, Esta_Activo: true }); FRACTALFOUNDS.transfer(msg.value); } // (2nd) mapping (address => Inversor) public Buscar_Inversor; // (3rd) function Realizar_Pago(address payable _client) external payable { require(msg.value > 0); _client.transfer(msg.value); Buscar_Inversor[_client].Esta_Activo = false; } // (4th) function Cambiar_Direccion_de_Fractal_Founds (address payable _direccion) external { require (msg.sender == owner); FRACTALFOUNDS = _direccion; } }
// SmartContract for Fractal Company - All Rights Reserved // :::::::::: ::::::::: ::: :::::::: ::::::::::: ::: ::: // :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: // +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ // :#::+::# +#++:++#: +#++:++#++: +#+ +#+ +#++:++#++: +#+ // +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ // #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# // ### ### ### ### ### ######## ### ### ### ##########
LineComment
Realizar_Pago
function Realizar_Pago(address payable _client) external payable { require(msg.value > 0); _client.transfer(msg.value); Buscar_Inversor[_client].Esta_Activo = false; }
// (3rd)
LineComment
v0.5.16+commit.9c3226ce
None
bzzr://7bb013355a608e8e376975a14c9666d4fc73b86a3416b76bb37a93e39da81ac4
{ "func_code_index": [ 923, 1129 ] }
4,929
Fractal
Fractal.sol
0xc9652efc267982b82df4ffd4bba5e0e7392f51f5
Solidity
Fractal
contract Fractal { struct Inversor { address inversor; uint Dia_de_la_inversion; uint Inversion_en_ETH; bool Esta_Activo; } // Fractal Founds Wallet (ETH) by default address owner = 0x78c25AA14b12fa53efDB77a5a46A59e0c571d0A6; address payable FRACTALFOUNDS = 0x78c25AA14b12fa53efDB77a5a46A59e0c571d0A6; //by default // (1st) function Invertir_Ahora() external payable { require(msg.value > 0); uint investment = msg.value; Buscar_Inversor[msg.sender] = Inversor({ inversor: msg.sender, Dia_de_la_inversion: block.timestamp, Inversion_en_ETH: investment, Esta_Activo: true }); FRACTALFOUNDS.transfer(msg.value); } // (2nd) mapping (address => Inversor) public Buscar_Inversor; // (3rd) function Realizar_Pago(address payable _client) external payable { require(msg.value > 0); _client.transfer(msg.value); Buscar_Inversor[_client].Esta_Activo = false; } // (4th) function Cambiar_Direccion_de_Fractal_Founds (address payable _direccion) external { require (msg.sender == owner); FRACTALFOUNDS = _direccion; } }
// SmartContract for Fractal Company - All Rights Reserved // :::::::::: ::::::::: ::: :::::::: ::::::::::: ::: ::: // :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: // +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ // :#::+::# +#++:++#: +#++:++#++: +#+ +#+ +#++:++#++: +#+ // +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ // #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# // ### ### ### ### ### ######## ### ### ### ##########
LineComment
Cambiar_Direccion_de_Fractal_Founds
function Cambiar_Direccion_de_Fractal_Founds (address payable _direccion) external { require (msg.sender == owner); FRACTALFOUNDS = _direccion; }
// (4th)
LineComment
v0.5.16+commit.9c3226ce
None
bzzr://7bb013355a608e8e376975a14c9666d4fc73b86a3416b76bb37a93e39da81ac4
{ "func_code_index": [ 1150, 1323 ] }
4,930
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
today
function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); }
/** * @dev returns the day number of the current day, in days since the UNIX epoch. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 5531, 5669 ] }
4,931
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
withdraw
function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); }
/** withdraw function */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 7867, 8521 ] }
4,932
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
zapCook
function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); }
// Zap into Cook staking pool functions
LineComment
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 11908, 12223 ] }
4,933
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
setPriceBasedMaxStep
function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; }
// Admin Functions
LineComment
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 12250, 12455 ] }
4,934
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
addAddressWithAllocation
function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); }
/** * add adddress with allocation */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 12513, 13055 ] }
4,935
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
addMultipleAddressWithAllocations
function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } }
/** * Add multiple address with multiple allocations */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 13131, 13984 ] }
4,936
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
blacklistAddress
function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; }
// Put an evil address into blacklist
LineComment
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 16713, 16915 ] }
4,937
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
removeAddressFromBlacklist
function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; }
//Remove an address from blacklist
LineComment
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 16958, 17171 ] }
4,938
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
pauseClaim
function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; }
// Pause all claim due to emergency
LineComment
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 17215, 17355 ] }
4,939
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
resumeCliam
function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; }
// resume cliamable
LineComment
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 17383, 17525 ] }
4,940
CookDistribution
contracts/core/CookDistribution.sol
0xb4d9dd5cb9e40c1a51e0e47f5110a643c28b0301
Solidity
CookDistribution
contract CookDistribution is Ownable, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event AllocationRegistered(address indexed beneficiary, uint256 amount); event TokensWithdrawal(address userAddress, uint256 amount); struct Allocation { uint256 amount; uint256 released; bool blackListed; bool isRegistered; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // oracle price data (dayNumber => price) mapping(uint256 => uint256) private _oraclePriceFeed; // all beneficiary address1 address[] private _allBeneficiary; // vesting start time unix uint256 public _start; // vesting duration in day uint256 public _duration; // vesting interval uint32 public _interval; // released percentage triggered by price, should divided by 100 uint256 public _advancePercentage; // last released percentage triggered date in dayNumber uint256 public _lastPriceUnlockDay; // next step to unlock uint32 public _nextPriceUnlockStep; // Max step can be moved uint32 public _maxPriceUnlockMoveStep; IERC20 private _token; IOracle private _oracle; IPriceConsumerV3 private _priceConsumer; // Date-related constants for sanity-checking dates to reject obvious erroneous inputs // SECONDS_PER_DAY = 30 for test only uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */ uint256[] private _priceKey; uint256[] private _percentageValue; mapping(uint256 => uint256) private _pricePercentageMapping; // Fields for Admin // stop everyone from claiming/zapping cook token due to emgergency bool public _pauseClaim; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256 start, // in unix uint256 duration, // in day uint32 interval, // in day address oracle_, address priceConsumer_ ) public { // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true); emit AllocationRegistered(beneficiaries_[i], amounts_[i]); } _token = token_; _duration = duration; _start = start; _interval = interval; // init release percentage is 1% _advancePercentage = 1; _oracle = IOracle(oracle_); _priceConsumer = IPriceConsumerV3(priceConsumer_); _lastPriceUnlockDay = 0; _nextPriceUnlockStep = 0; _maxPriceUnlockMoveStep = 1; _pauseClaim = false; // init price percentage _priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000, 4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000]; _percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; for (uint256 i = 0; i < _priceKey.length; i++) { _pricePercentageMapping[_priceKey[i]] = _percentageValue[i]; } // Make the deployer defaul admin role and manager role _setupRole(MANAGER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE); } fallback() external payable { revert(); } function setStart(uint256 start) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _start = start; } function setDuration(uint256 duration) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _duration = duration; } function setInvertal(uint32 interval) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _interval = interval; } function setAdvancePercentage(uint256 advancePercentage) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _advancePercentage = advancePercentage; } function getRegisteredStatus(address userAddress) public view returns (bool) { return _beneficiaryAllocations[userAddress].isRegistered; } function getUserVestingAmount(address userAddress) public view returns (uint256) { return _beneficiaryAllocations[userAddress].amount; } function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) { uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released); return avalible; } function getUserVestedAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256 amountVested) { return _getVestedAmount(userAddress, onDayOrToday); } /** * @dev returns the day number of the current day, in days since the UNIX epoch. */ function today() public view virtual returns (uint256 dayNumber) { return uint256(block.timestamp / SECONDS_PER_DAY); } function startDay() public view returns (uint256) { return uint256(_start / SECONDS_PER_DAY); } function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) { return onDayOrToday == 0 ? today() : onDayOrToday; } function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) { uint256 onDay = _effectiveDay(onDayOrToday); // day // If after end of vesting, then the vested amount is total amount. if (onDay >= (startDay() + _duration)) { return _beneficiaryAllocations[userAddress].amount; } // If it's before the vesting then the vested amount is zero. else if (onDay < startDay()) { // All are vested (none are not vested) return 0; } // Otherwise a fractional amount is vested. else { // Compute the exact number of days vested. uint256 daysVested = onDay - startDay(); // Adjust result rounding down to take into consideration the interval. uint256 effectiveDaysVested = (daysVested / _interval) * _interval; uint256 vested = 0; if ( _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration) > _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100) ) { // no price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(effectiveDaysVested) .div(_duration); } else { // price based percentage > date based percentage vested = _beneficiaryAllocations[userAddress] .amount .mul(_advancePercentage) .div(100); } return vested; } } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Not claimable due to emgergency"); require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.safeTransfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) { // get pair address IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); uint256 reserve0; uint256 reserve1; address weth; if (lpPair.token0() == address(_token)) { (reserve0, reserve1, ) = lpPair.getReserves(); weth = lpPair.token1(); } else { (reserve1, reserve0, ) = lpPair.getReserves(); weth = lpPair.token0(); } uint256 wethAmount = (reserve0 == 0 && reserve1 == 0) ? cookAmount : UniswapV2Library.quote(cookAmount, reserve0, reserve1); return (wethAmount, weth); } function zapLP(uint256 cookAmount, address poolAddress) external { _zapLP(cookAmount, poolAddress, false); } function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); uint256 newUniv2 = 0; (, newUniv2) = addLiquidity(cookAmount); IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2); IPool(poolAddress).zapStake(newUniv2, userAddress); } function _checkValidZap(address userAddress, uint256 cookAmount) internal { require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address."); require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted."); require(_pauseClaim == false, "Cook token can not be zap."); require(cookAmount > 0, "zero zap amount"); require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount); } function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) { // get pair address (uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount); _token.safeTransfer(_oracle.pairAddress(), cookAmount); IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress()); if (lpPair.token0() == address(_token)) { // token0 == cook, token1 == weth require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token1()).safeTransferFrom( msg.sender, _oracle.pairAddress(), wethAmount ); } else if (lpPair.token1() == address(_token)) { // token0 == weth, token1 == cook require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance"); require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance"); IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount); } return (wethAmount, lpPair.mint(address(this))); } // Zap into Cook staking pool functions function zapCook(uint256 cookAmount, address cookPoolAddress) external { address userAddress = msg.sender; _checkValidZap(userAddress, cookAmount); IERC20(address(_token)).approve(cookPoolAddress, cookAmount); IPool(cookPoolAddress).zapStake(cookAmount, userAddress); } // Admin Functions function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _maxPriceUnlockMoveStep = newMaxPriceBasedStep; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddress].isRegistered = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true ); emit AllocationRegistered(beneficiaryAddress, amount); } /** * Add multiple address with multiple allocations */ function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input"); for (uint256 i = 0; i < beneficiaryAddresses.length; i++) { require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits."); _beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true; _beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true); emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]); } } function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0; require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); for (uint256 i = 0; i < _allBeneficiary.length; ++i) { totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today()); } return totalAvailable; } function getLatestSevenSMA() public view returns (uint256) { // 7 day sma uint256 priceSum = uint256(0); uint256 priceCount = uint256(0); for (uint32 i = 0; i < 7; ++i) { if (_oraclePriceFeed[today() - i] != 0) { priceSum = priceSum + _oraclePriceFeed[today() - i]; priceCount += 1; } } uint256 sevenSMA = 0; if (priceCount == 7) { sevenSMA = priceSum.div(priceCount); } return sevenSMA; } function updatePriceFeed() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); // oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH uint256 cookPrice = _oracle.update(); // ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD uint256 ethPrice = uint256(_priceConsumer.getLatestPrice()); uint256 price = cookPrice.mul(ethPrice).div(10**18); // update price to _oraclePriceFeed _oraclePriceFeed[today()] = price; if (today() >= _lastPriceUnlockDay.add(7)) { // 7 day sma uint256 sevenSMA = getLatestSevenSMA(); uint256 priceRef = 0; for (uint32 i = 0; i < _priceKey.length; ++i) { if (sevenSMA >= _priceKey[i]) { priceRef = _pricePercentageMapping[_priceKey[i]]; } } // no lower action if the price drop after price-based unlock if (priceRef > _advancePercentage) { // guard _nextPriceUnlockStep exceed if (_nextPriceUnlockStep >= _percentageValue.length) { _nextPriceUnlockStep = uint32(_percentageValue.length - 1); } // update _advancePercentage to nextStep percentage _advancePercentage = _pricePercentageMapping[ _priceKey[_nextPriceUnlockStep] ]; // update nextStep value _nextPriceUnlockStep = _nextPriceUnlockStep + _maxPriceUnlockMoveStep; // update lastUnlcokDay _lastPriceUnlockDay = today(); } } } // Put an evil address into blacklist function blacklistAddress(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = true; } //Remove an address from blacklist function removeAddressFromBlacklist(address userAddress) public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _beneficiaryAllocations[userAddress].blackListed = false; } // Pause all claim due to emergency function pauseClaim() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = true; } // resume cliamable function resumeCliam() public { require(hasRole(MANAGER_ROLE, msg.sender), "only manager"); _pauseClaim = false; } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); } function getManagerRole() public returns (bytes32) { return MANAGER_ROLE; } }
/** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. */
NatSpecMultiLine
emergencyWithdraw
function emergencyWithdraw(uint256 amount) public onlyOwner { _token.safeTransfer(msg.sender, amount); }
// admin emergency to transfer token to owner
LineComment
v0.6.2+commit.bacdbe57
MIT
ipfs://be8b6d5abcf228e898a25260316712bae59fe3232df1fc6ee5aa0bddce3e9250
{ "func_code_index": [ 17579, 17702 ] }
4,941
FxRates
contracts/FxRates.sol
0x27f2d2d38c6a7863c7554f357af02f648773361a
Solidity
FxRates
contract FxRates is Ownable { using SafeMath for uint256; struct Rate { string rate; string timestamp; } /** * @dev Event for logging an update of the exchange rates * @param symbol one of ["ETH", "BTC"] * @param updateNumber an incremental number giving the number of update * @param timestamp human readable timestamp of the earliest validity time * @param rate a string containing the rate value */ event RateUpdate(string symbol, uint256 updateNumber, string timestamp, string rate); uint256 public numberBtcUpdates = 0; mapping(uint256 => Rate) public btcUpdates; uint256 public numberEthUpdates = 0; mapping(uint256 => Rate) public ethUpdates; /** * @dev Adds the latest Ether Euro rate to the history. Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateEthRate(string _rate, string _timestamp) public onlyOwner { numberEthUpdates = numberEthUpdates.add(1); ethUpdates[numberEthUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("ETH", numberEthUpdates, _timestamp, _rate); } /** * @dev Adds the latest Btc Euro rate to the history. . Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateBtcRate(string _rate, string _timestamp) public onlyOwner { numberBtcUpdates = numberBtcUpdates.add(1); btcUpdates[numberBtcUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("BTC", numberBtcUpdates, _timestamp, _rate); } /** * @dev Gets the latest Eth Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getEthRate() public view returns(Rate) { /* require(numberEthUpdates > 0); */ return ethUpdates[numberEthUpdates]; /* ethUpdates[numberEthUpdates].rate, */ /* ethUpdates[numberEthUpdates].timestamp */ /* ); */ } /** * @dev Gets the latest Btc Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getBtcRate() public view returns(string, string) { /* require(numberBtcUpdates > 0); */ return ( btcUpdates[numberBtcUpdates].rate, btcUpdates[numberBtcUpdates].timestamp ); } /** * @dev Gets the historic Eth Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistEthRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberEthUpdates); return ( ethUpdates[_updateNumber].rate, ethUpdates[_updateNumber].timestamp ); } /** * @dev Gets the historic Btc Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistBtcRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberBtcUpdates); return ( btcUpdates[_updateNumber].rate, btcUpdates[_updateNumber].timestamp ); } }
/** * @title FxRates * @dev Store the historic fx rates for conversion ETHEUR and BTCEUR */
NatSpecMultiLine
updateEthRate
function updateEthRate(string _rate, string _timestamp) public onlyOwner { numberEthUpdates = numberEthUpdates.add(1); ethUpdates[numberEthUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("ETH", numberEthUpdates, _timestamp, _rate); }
/** * @dev Adds the latest Ether Euro rate to the history. Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://239c8caaa3f6afba08237b811d97c7e646ccca04f115ba2b84c27ef37df81b10
{ "func_code_index": [ 1013, 1338 ] }
4,942
FxRates
contracts/FxRates.sol
0x27f2d2d38c6a7863c7554f357af02f648773361a
Solidity
FxRates
contract FxRates is Ownable { using SafeMath for uint256; struct Rate { string rate; string timestamp; } /** * @dev Event for logging an update of the exchange rates * @param symbol one of ["ETH", "BTC"] * @param updateNumber an incremental number giving the number of update * @param timestamp human readable timestamp of the earliest validity time * @param rate a string containing the rate value */ event RateUpdate(string symbol, uint256 updateNumber, string timestamp, string rate); uint256 public numberBtcUpdates = 0; mapping(uint256 => Rate) public btcUpdates; uint256 public numberEthUpdates = 0; mapping(uint256 => Rate) public ethUpdates; /** * @dev Adds the latest Ether Euro rate to the history. Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateEthRate(string _rate, string _timestamp) public onlyOwner { numberEthUpdates = numberEthUpdates.add(1); ethUpdates[numberEthUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("ETH", numberEthUpdates, _timestamp, _rate); } /** * @dev Adds the latest Btc Euro rate to the history. . Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateBtcRate(string _rate, string _timestamp) public onlyOwner { numberBtcUpdates = numberBtcUpdates.add(1); btcUpdates[numberBtcUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("BTC", numberBtcUpdates, _timestamp, _rate); } /** * @dev Gets the latest Eth Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getEthRate() public view returns(Rate) { /* require(numberEthUpdates > 0); */ return ethUpdates[numberEthUpdates]; /* ethUpdates[numberEthUpdates].rate, */ /* ethUpdates[numberEthUpdates].timestamp */ /* ); */ } /** * @dev Gets the latest Btc Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getBtcRate() public view returns(string, string) { /* require(numberBtcUpdates > 0); */ return ( btcUpdates[numberBtcUpdates].rate, btcUpdates[numberBtcUpdates].timestamp ); } /** * @dev Gets the historic Eth Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistEthRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberEthUpdates); return ( ethUpdates[_updateNumber].rate, ethUpdates[_updateNumber].timestamp ); } /** * @dev Gets the historic Btc Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistBtcRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberBtcUpdates); return ( btcUpdates[_updateNumber].rate, btcUpdates[_updateNumber].timestamp ); } }
/** * @title FxRates * @dev Store the historic fx rates for conversion ETHEUR and BTCEUR */
NatSpecMultiLine
updateBtcRate
function updateBtcRate(string _rate, string _timestamp) public onlyOwner { numberBtcUpdates = numberBtcUpdates.add(1); btcUpdates[numberBtcUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("BTC", numberBtcUpdates, _timestamp, _rate); }
/** * @dev Adds the latest Btc Euro rate to the history. . Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://239c8caaa3f6afba08237b811d97c7e646ccca04f115ba2b84c27ef37df81b10
{ "func_code_index": [ 1590, 1915 ] }
4,943
FxRates
contracts/FxRates.sol
0x27f2d2d38c6a7863c7554f357af02f648773361a
Solidity
FxRates
contract FxRates is Ownable { using SafeMath for uint256; struct Rate { string rate; string timestamp; } /** * @dev Event for logging an update of the exchange rates * @param symbol one of ["ETH", "BTC"] * @param updateNumber an incremental number giving the number of update * @param timestamp human readable timestamp of the earliest validity time * @param rate a string containing the rate value */ event RateUpdate(string symbol, uint256 updateNumber, string timestamp, string rate); uint256 public numberBtcUpdates = 0; mapping(uint256 => Rate) public btcUpdates; uint256 public numberEthUpdates = 0; mapping(uint256 => Rate) public ethUpdates; /** * @dev Adds the latest Ether Euro rate to the history. Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateEthRate(string _rate, string _timestamp) public onlyOwner { numberEthUpdates = numberEthUpdates.add(1); ethUpdates[numberEthUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("ETH", numberEthUpdates, _timestamp, _rate); } /** * @dev Adds the latest Btc Euro rate to the history. . Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateBtcRate(string _rate, string _timestamp) public onlyOwner { numberBtcUpdates = numberBtcUpdates.add(1); btcUpdates[numberBtcUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("BTC", numberBtcUpdates, _timestamp, _rate); } /** * @dev Gets the latest Eth Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getEthRate() public view returns(Rate) { /* require(numberEthUpdates > 0); */ return ethUpdates[numberEthUpdates]; /* ethUpdates[numberEthUpdates].rate, */ /* ethUpdates[numberEthUpdates].timestamp */ /* ); */ } /** * @dev Gets the latest Btc Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getBtcRate() public view returns(string, string) { /* require(numberBtcUpdates > 0); */ return ( btcUpdates[numberBtcUpdates].rate, btcUpdates[numberBtcUpdates].timestamp ); } /** * @dev Gets the historic Eth Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistEthRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberEthUpdates); return ( ethUpdates[_updateNumber].rate, ethUpdates[_updateNumber].timestamp ); } /** * @dev Gets the historic Btc Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistBtcRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberBtcUpdates); return ( btcUpdates[_updateNumber].rate, btcUpdates[_updateNumber].timestamp ); } }
/** * @title FxRates * @dev Store the historic fx rates for conversion ETHEUR and BTCEUR */
NatSpecMultiLine
getEthRate
function getEthRate() public view returns(Rate) { /* require(numberEthUpdates > 0); */ return ethUpdates[numberEthUpdates]; /* ethUpdates[numberEthUpdates].rate, */ /* ethUpdates[numberEthUpdates].timestamp */ /* ); */ }
/** * @dev Gets the latest Eth Euro rate * @return a tuple containing the rate and the timestamp in human readable format */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://239c8caaa3f6afba08237b811d97c7e646ccca04f115ba2b84c27ef37df81b10
{ "func_code_index": [ 2066, 2349 ] }
4,944
FxRates
contracts/FxRates.sol
0x27f2d2d38c6a7863c7554f357af02f648773361a
Solidity
FxRates
contract FxRates is Ownable { using SafeMath for uint256; struct Rate { string rate; string timestamp; } /** * @dev Event for logging an update of the exchange rates * @param symbol one of ["ETH", "BTC"] * @param updateNumber an incremental number giving the number of update * @param timestamp human readable timestamp of the earliest validity time * @param rate a string containing the rate value */ event RateUpdate(string symbol, uint256 updateNumber, string timestamp, string rate); uint256 public numberBtcUpdates = 0; mapping(uint256 => Rate) public btcUpdates; uint256 public numberEthUpdates = 0; mapping(uint256 => Rate) public ethUpdates; /** * @dev Adds the latest Ether Euro rate to the history. Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateEthRate(string _rate, string _timestamp) public onlyOwner { numberEthUpdates = numberEthUpdates.add(1); ethUpdates[numberEthUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("ETH", numberEthUpdates, _timestamp, _rate); } /** * @dev Adds the latest Btc Euro rate to the history. . Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateBtcRate(string _rate, string _timestamp) public onlyOwner { numberBtcUpdates = numberBtcUpdates.add(1); btcUpdates[numberBtcUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("BTC", numberBtcUpdates, _timestamp, _rate); } /** * @dev Gets the latest Eth Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getEthRate() public view returns(Rate) { /* require(numberEthUpdates > 0); */ return ethUpdates[numberEthUpdates]; /* ethUpdates[numberEthUpdates].rate, */ /* ethUpdates[numberEthUpdates].timestamp */ /* ); */ } /** * @dev Gets the latest Btc Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getBtcRate() public view returns(string, string) { /* require(numberBtcUpdates > 0); */ return ( btcUpdates[numberBtcUpdates].rate, btcUpdates[numberBtcUpdates].timestamp ); } /** * @dev Gets the historic Eth Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistEthRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberEthUpdates); return ( ethUpdates[_updateNumber].rate, ethUpdates[_updateNumber].timestamp ); } /** * @dev Gets the historic Btc Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistBtcRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberBtcUpdates); return ( btcUpdates[_updateNumber].rate, btcUpdates[_updateNumber].timestamp ); } }
/** * @title FxRates * @dev Store the historic fx rates for conversion ETHEUR and BTCEUR */
NatSpecMultiLine
getBtcRate
function getBtcRate() public view returns(string, string) { /* require(numberBtcUpdates > 0); */ return ( btcUpdates[numberBtcUpdates].rate, btcUpdates[numberBtcUpdates].timestamp ); }
/** * @dev Gets the latest Btc Euro rate * @return a tuple containing the rate and the timestamp in human readable format */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://239c8caaa3f6afba08237b811d97c7e646ccca04f115ba2b84c27ef37df81b10
{ "func_code_index": [ 2500, 2747 ] }
4,945
FxRates
contracts/FxRates.sol
0x27f2d2d38c6a7863c7554f357af02f648773361a
Solidity
FxRates
contract FxRates is Ownable { using SafeMath for uint256; struct Rate { string rate; string timestamp; } /** * @dev Event for logging an update of the exchange rates * @param symbol one of ["ETH", "BTC"] * @param updateNumber an incremental number giving the number of update * @param timestamp human readable timestamp of the earliest validity time * @param rate a string containing the rate value */ event RateUpdate(string symbol, uint256 updateNumber, string timestamp, string rate); uint256 public numberBtcUpdates = 0; mapping(uint256 => Rate) public btcUpdates; uint256 public numberEthUpdates = 0; mapping(uint256 => Rate) public ethUpdates; /** * @dev Adds the latest Ether Euro rate to the history. Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateEthRate(string _rate, string _timestamp) public onlyOwner { numberEthUpdates = numberEthUpdates.add(1); ethUpdates[numberEthUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("ETH", numberEthUpdates, _timestamp, _rate); } /** * @dev Adds the latest Btc Euro rate to the history. . Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateBtcRate(string _rate, string _timestamp) public onlyOwner { numberBtcUpdates = numberBtcUpdates.add(1); btcUpdates[numberBtcUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("BTC", numberBtcUpdates, _timestamp, _rate); } /** * @dev Gets the latest Eth Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getEthRate() public view returns(Rate) { /* require(numberEthUpdates > 0); */ return ethUpdates[numberEthUpdates]; /* ethUpdates[numberEthUpdates].rate, */ /* ethUpdates[numberEthUpdates].timestamp */ /* ); */ } /** * @dev Gets the latest Btc Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getBtcRate() public view returns(string, string) { /* require(numberBtcUpdates > 0); */ return ( btcUpdates[numberBtcUpdates].rate, btcUpdates[numberBtcUpdates].timestamp ); } /** * @dev Gets the historic Eth Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistEthRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberEthUpdates); return ( ethUpdates[_updateNumber].rate, ethUpdates[_updateNumber].timestamp ); } /** * @dev Gets the historic Btc Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistBtcRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberBtcUpdates); return ( btcUpdates[_updateNumber].rate, btcUpdates[_updateNumber].timestamp ); } }
/** * @title FxRates * @dev Store the historic fx rates for conversion ETHEUR and BTCEUR */
NatSpecMultiLine
getHistEthRate
function getHistEthRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberEthUpdates); return ( ethUpdates[_updateNumber].rate, ethUpdates[_updateNumber].timestamp ); }
/** * @dev Gets the historic Eth Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://239c8caaa3f6afba08237b811d97c7e646ccca04f115ba2b84c27ef37df81b10
{ "func_code_index": [ 2979, 3252 ] }
4,946
FxRates
contracts/FxRates.sol
0x27f2d2d38c6a7863c7554f357af02f648773361a
Solidity
FxRates
contract FxRates is Ownable { using SafeMath for uint256; struct Rate { string rate; string timestamp; } /** * @dev Event for logging an update of the exchange rates * @param symbol one of ["ETH", "BTC"] * @param updateNumber an incremental number giving the number of update * @param timestamp human readable timestamp of the earliest validity time * @param rate a string containing the rate value */ event RateUpdate(string symbol, uint256 updateNumber, string timestamp, string rate); uint256 public numberBtcUpdates = 0; mapping(uint256 => Rate) public btcUpdates; uint256 public numberEthUpdates = 0; mapping(uint256 => Rate) public ethUpdates; /** * @dev Adds the latest Ether Euro rate to the history. Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateEthRate(string _rate, string _timestamp) public onlyOwner { numberEthUpdates = numberEthUpdates.add(1); ethUpdates[numberEthUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("ETH", numberEthUpdates, _timestamp, _rate); } /** * @dev Adds the latest Btc Euro rate to the history. . Only the crontract owner can execute this. * @param _rate the exchange rate * @param _timestamp human readable earliest point in time where the rate is valid */ function updateBtcRate(string _rate, string _timestamp) public onlyOwner { numberBtcUpdates = numberBtcUpdates.add(1); btcUpdates[numberBtcUpdates] = Rate({ rate: _rate, timestamp: _timestamp }); RateUpdate("BTC", numberBtcUpdates, _timestamp, _rate); } /** * @dev Gets the latest Eth Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getEthRate() public view returns(Rate) { /* require(numberEthUpdates > 0); */ return ethUpdates[numberEthUpdates]; /* ethUpdates[numberEthUpdates].rate, */ /* ethUpdates[numberEthUpdates].timestamp */ /* ); */ } /** * @dev Gets the latest Btc Euro rate * @return a tuple containing the rate and the timestamp in human readable format */ function getBtcRate() public view returns(string, string) { /* require(numberBtcUpdates > 0); */ return ( btcUpdates[numberBtcUpdates].rate, btcUpdates[numberBtcUpdates].timestamp ); } /** * @dev Gets the historic Eth Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistEthRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberEthUpdates); return ( ethUpdates[_updateNumber].rate, ethUpdates[_updateNumber].timestamp ); } /** * @dev Gets the historic Btc Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */ function getHistBtcRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberBtcUpdates); return ( btcUpdates[_updateNumber].rate, btcUpdates[_updateNumber].timestamp ); } }
/** * @title FxRates * @dev Store the historic fx rates for conversion ETHEUR and BTCEUR */
NatSpecMultiLine
getHistBtcRate
function getHistBtcRate(uint256 _updateNumber) public view returns(string, string) { require(_updateNumber <= numberBtcUpdates); return ( btcUpdates[_updateNumber].rate, btcUpdates[_updateNumber].timestamp ); }
/** * @dev Gets the historic Btc Euro rate * @param _updateNumber the number of the update the rate corresponds to. * @return a tuple containing the rate and the timestamp in human readable format */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://239c8caaa3f6afba08237b811d97c7e646ccca04f115ba2b84c27ef37df81b10
{ "func_code_index": [ 3484, 3757 ] }
4,947
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicUtils
contract AtomicUtils{ // ETH and its wrappers address constant WETHAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IWETH constant WETH = IWETH(WETHAddress); Token constant ETH = Token(address(0)); address constant EEEAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; Token constant EEE = Token(EEEAddress); // Universal function to query this contracts balance, supporting and Token function balanceOf(Token token) internal view returns(uint balance){ if(isETH(token)){ return address(this).balance; }else{ return token.balanceOf(address(this)); } } // Universal send function, supporting ETH and Token function send(Token token, address payable recipient, uint amount) internal { if(isETH(token)){ require( recipient.send(amount), "Sending of ETH failed." ); }else{ Token(token).transfer(recipient, amount); require( validateOptionalERC20Return(), "ERC20 token transfer failed." ); } } // Universal function to claim tokens from msg.sender function claimTokenFromSenderTo(Token _token, uint _amount, address _receiver) internal { if (isETH(_token)) { require(msg.value == _amount); // dont forward ETH }else{ require(msg.value == 0); _token.transferFrom(msg.sender, _receiver, _amount); } } // Token approval function supporting non-compliant tokens function approve(Token _token, address _spender, uint _amount) internal { if (!isETH(_token)) { _token.approve(_spender, _amount); require( validateOptionalERC20Return(), "ERC20 approval failed." ); } } // Validate return data of non-compliant erc20s function validateOptionalERC20Return() pure internal returns (bool){ uint256 success = 0; assembly { switch returndatasize() // Check the number of bytes the token contract returned case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded success := 1 } case 32 { // 32 bytes returned, result is the returned bool returndatacopy(0, 0, 32) success := mload(0) } } return success != 0; } function isETH(Token token) pure internal returns (bool){ if( address(token) == address(0) || address(token) == EEEAddress ){ return true; }else{ return false; } } function isWETH(Token token) pure internal returns (bool){ if(address(token) == WETHAddress){ return true; }else{ return false; } } // Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol function sliceBytes( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } }
balanceOf
function balanceOf(Token token) internal view returns(uint balance){ if(isETH(token)){ return address(this).balance; }else{ return token.balanceOf(address(this)); } }
// Universal function to query this contracts balance, supporting and Token
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 440, 669 ] }
4,948
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicUtils
contract AtomicUtils{ // ETH and its wrappers address constant WETHAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IWETH constant WETH = IWETH(WETHAddress); Token constant ETH = Token(address(0)); address constant EEEAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; Token constant EEE = Token(EEEAddress); // Universal function to query this contracts balance, supporting and Token function balanceOf(Token token) internal view returns(uint balance){ if(isETH(token)){ return address(this).balance; }else{ return token.balanceOf(address(this)); } } // Universal send function, supporting ETH and Token function send(Token token, address payable recipient, uint amount) internal { if(isETH(token)){ require( recipient.send(amount), "Sending of ETH failed." ); }else{ Token(token).transfer(recipient, amount); require( validateOptionalERC20Return(), "ERC20 token transfer failed." ); } } // Universal function to claim tokens from msg.sender function claimTokenFromSenderTo(Token _token, uint _amount, address _receiver) internal { if (isETH(_token)) { require(msg.value == _amount); // dont forward ETH }else{ require(msg.value == 0); _token.transferFrom(msg.sender, _receiver, _amount); } } // Token approval function supporting non-compliant tokens function approve(Token _token, address _spender, uint _amount) internal { if (!isETH(_token)) { _token.approve(_spender, _amount); require( validateOptionalERC20Return(), "ERC20 approval failed." ); } } // Validate return data of non-compliant erc20s function validateOptionalERC20Return() pure internal returns (bool){ uint256 success = 0; assembly { switch returndatasize() // Check the number of bytes the token contract returned case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded success := 1 } case 32 { // 32 bytes returned, result is the returned bool returndatacopy(0, 0, 32) success := mload(0) } } return success != 0; } function isETH(Token token) pure internal returns (bool){ if( address(token) == address(0) || address(token) == EEEAddress ){ return true; }else{ return false; } } function isWETH(Token token) pure internal returns (bool){ if(address(token) == WETHAddress){ return true; }else{ return false; } } // Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol function sliceBytes( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } }
send
function send(Token token, address payable recipient, uint amount) internal { if(isETH(token)){ require( recipient.send(amount), "Sending of ETH failed." ); }else{ Token(token).transfer(recipient, amount); require( validateOptionalERC20Return(), "ERC20 token transfer failed." ); } }
// Universal send function, supporting ETH and Token
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 734, 1187 ] }
4,949
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicUtils
contract AtomicUtils{ // ETH and its wrappers address constant WETHAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IWETH constant WETH = IWETH(WETHAddress); Token constant ETH = Token(address(0)); address constant EEEAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; Token constant EEE = Token(EEEAddress); // Universal function to query this contracts balance, supporting and Token function balanceOf(Token token) internal view returns(uint balance){ if(isETH(token)){ return address(this).balance; }else{ return token.balanceOf(address(this)); } } // Universal send function, supporting ETH and Token function send(Token token, address payable recipient, uint amount) internal { if(isETH(token)){ require( recipient.send(amount), "Sending of ETH failed." ); }else{ Token(token).transfer(recipient, amount); require( validateOptionalERC20Return(), "ERC20 token transfer failed." ); } } // Universal function to claim tokens from msg.sender function claimTokenFromSenderTo(Token _token, uint _amount, address _receiver) internal { if (isETH(_token)) { require(msg.value == _amount); // dont forward ETH }else{ require(msg.value == 0); _token.transferFrom(msg.sender, _receiver, _amount); } } // Token approval function supporting non-compliant tokens function approve(Token _token, address _spender, uint _amount) internal { if (!isETH(_token)) { _token.approve(_spender, _amount); require( validateOptionalERC20Return(), "ERC20 approval failed." ); } } // Validate return data of non-compliant erc20s function validateOptionalERC20Return() pure internal returns (bool){ uint256 success = 0; assembly { switch returndatasize() // Check the number of bytes the token contract returned case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded success := 1 } case 32 { // 32 bytes returned, result is the returned bool returndatacopy(0, 0, 32) success := mload(0) } } return success != 0; } function isETH(Token token) pure internal returns (bool){ if( address(token) == address(0) || address(token) == EEEAddress ){ return true; }else{ return false; } } function isWETH(Token token) pure internal returns (bool){ if(address(token) == WETHAddress){ return true; }else{ return false; } } // Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol function sliceBytes( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } }
claimTokenFromSenderTo
function claimTokenFromSenderTo(Token _token, uint _amount, address _receiver) internal { if (isETH(_token)) { require(msg.value == _amount); // dont forward ETH }else{ require(msg.value == 0); _token.transferFrom(msg.sender, _receiver, _amount); } }
// Universal function to claim tokens from msg.sender
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 1253, 1593 ] }
4,950
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicUtils
contract AtomicUtils{ // ETH and its wrappers address constant WETHAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IWETH constant WETH = IWETH(WETHAddress); Token constant ETH = Token(address(0)); address constant EEEAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; Token constant EEE = Token(EEEAddress); // Universal function to query this contracts balance, supporting and Token function balanceOf(Token token) internal view returns(uint balance){ if(isETH(token)){ return address(this).balance; }else{ return token.balanceOf(address(this)); } } // Universal send function, supporting ETH and Token function send(Token token, address payable recipient, uint amount) internal { if(isETH(token)){ require( recipient.send(amount), "Sending of ETH failed." ); }else{ Token(token).transfer(recipient, amount); require( validateOptionalERC20Return(), "ERC20 token transfer failed." ); } } // Universal function to claim tokens from msg.sender function claimTokenFromSenderTo(Token _token, uint _amount, address _receiver) internal { if (isETH(_token)) { require(msg.value == _amount); // dont forward ETH }else{ require(msg.value == 0); _token.transferFrom(msg.sender, _receiver, _amount); } } // Token approval function supporting non-compliant tokens function approve(Token _token, address _spender, uint _amount) internal { if (!isETH(_token)) { _token.approve(_spender, _amount); require( validateOptionalERC20Return(), "ERC20 approval failed." ); } } // Validate return data of non-compliant erc20s function validateOptionalERC20Return() pure internal returns (bool){ uint256 success = 0; assembly { switch returndatasize() // Check the number of bytes the token contract returned case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded success := 1 } case 32 { // 32 bytes returned, result is the returned bool returndatacopy(0, 0, 32) success := mload(0) } } return success != 0; } function isETH(Token token) pure internal returns (bool){ if( address(token) == address(0) || address(token) == EEEAddress ){ return true; }else{ return false; } } function isWETH(Token token) pure internal returns (bool){ if(address(token) == WETHAddress){ return true; }else{ return false; } } // Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol function sliceBytes( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } }
approve
function approve(Token _token, address _spender, uint _amount) internal { if (!isETH(_token)) { _token.approve(_spender, _amount); require( validateOptionalERC20Return(), "ERC20 approval failed." ); } }
// Token approval function supporting non-compliant tokens
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 1664, 1967 ] }
4,951
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicUtils
contract AtomicUtils{ // ETH and its wrappers address constant WETHAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IWETH constant WETH = IWETH(WETHAddress); Token constant ETH = Token(address(0)); address constant EEEAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; Token constant EEE = Token(EEEAddress); // Universal function to query this contracts balance, supporting and Token function balanceOf(Token token) internal view returns(uint balance){ if(isETH(token)){ return address(this).balance; }else{ return token.balanceOf(address(this)); } } // Universal send function, supporting ETH and Token function send(Token token, address payable recipient, uint amount) internal { if(isETH(token)){ require( recipient.send(amount), "Sending of ETH failed." ); }else{ Token(token).transfer(recipient, amount); require( validateOptionalERC20Return(), "ERC20 token transfer failed." ); } } // Universal function to claim tokens from msg.sender function claimTokenFromSenderTo(Token _token, uint _amount, address _receiver) internal { if (isETH(_token)) { require(msg.value == _amount); // dont forward ETH }else{ require(msg.value == 0); _token.transferFrom(msg.sender, _receiver, _amount); } } // Token approval function supporting non-compliant tokens function approve(Token _token, address _spender, uint _amount) internal { if (!isETH(_token)) { _token.approve(_spender, _amount); require( validateOptionalERC20Return(), "ERC20 approval failed." ); } } // Validate return data of non-compliant erc20s function validateOptionalERC20Return() pure internal returns (bool){ uint256 success = 0; assembly { switch returndatasize() // Check the number of bytes the token contract returned case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded success := 1 } case 32 { // 32 bytes returned, result is the returned bool returndatacopy(0, 0, 32) success := mload(0) } } return success != 0; } function isETH(Token token) pure internal returns (bool){ if( address(token) == address(0) || address(token) == EEEAddress ){ return true; }else{ return false; } } function isWETH(Token token) pure internal returns (bool){ if(address(token) == WETHAddress){ return true; }else{ return false; } } // Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol function sliceBytes( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } }
validateOptionalERC20Return
function validateOptionalERC20Return() pure internal returns (bool){ uint256 success = 0; assembly { switch returndatasize() // Check the number of bytes the token contract returned case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded success := 1 } case 32 { // 32 bytes returned, result is the returned bool returndatacopy(0, 0, 32) success := mload(0) } } return success != 0; }
// Validate return data of non-compliant erc20s
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 2027, 2675 ] }
4,952
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicUtils
contract AtomicUtils{ // ETH and its wrappers address constant WETHAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IWETH constant WETH = IWETH(WETHAddress); Token constant ETH = Token(address(0)); address constant EEEAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; Token constant EEE = Token(EEEAddress); // Universal function to query this contracts balance, supporting and Token function balanceOf(Token token) internal view returns(uint balance){ if(isETH(token)){ return address(this).balance; }else{ return token.balanceOf(address(this)); } } // Universal send function, supporting ETH and Token function send(Token token, address payable recipient, uint amount) internal { if(isETH(token)){ require( recipient.send(amount), "Sending of ETH failed." ); }else{ Token(token).transfer(recipient, amount); require( validateOptionalERC20Return(), "ERC20 token transfer failed." ); } } // Universal function to claim tokens from msg.sender function claimTokenFromSenderTo(Token _token, uint _amount, address _receiver) internal { if (isETH(_token)) { require(msg.value == _amount); // dont forward ETH }else{ require(msg.value == 0); _token.transferFrom(msg.sender, _receiver, _amount); } } // Token approval function supporting non-compliant tokens function approve(Token _token, address _spender, uint _amount) internal { if (!isETH(_token)) { _token.approve(_spender, _amount); require( validateOptionalERC20Return(), "ERC20 approval failed." ); } } // Validate return data of non-compliant erc20s function validateOptionalERC20Return() pure internal returns (bool){ uint256 success = 0; assembly { switch returndatasize() // Check the number of bytes the token contract returned case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded success := 1 } case 32 { // 32 bytes returned, result is the returned bool returndatacopy(0, 0, 32) success := mload(0) } } return success != 0; } function isETH(Token token) pure internal returns (bool){ if( address(token) == address(0) || address(token) == EEEAddress ){ return true; }else{ return false; } } function isWETH(Token token) pure internal returns (bool){ if(address(token) == WETHAddress){ return true; }else{ return false; } } // Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol function sliceBytes( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } }
sliceBytes
function sliceBytes( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; }
// Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 3242, 5795 ] }
4,953
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicBlue
contract AtomicBlue is AtomicUtils, AtomicTypes{ // IMPORTANT NOTICE: // NEVER set a token allowance to this contract, as everybody can do arbitrary calls from it. // When swapping tokens always go through AtomicTokenProxy. // This contract assumes token to swap has already been transfered to it when being called. Ether can be sent directly with the call. // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams memory _swap, DistributionParams memory _distribution, address payable _receipient ) public payable returns (uint _output){ // execute swaps on behalf of trader _output = doDistributedSwap(_swap, _distribution); // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to receipient send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } function multiPathSwapAndSend( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution, address payable _receipient ) public payable returns (uint _output){ // verify path require( _path[0] == _swap.sellToken && _path[_path.length - 1] == _swap.buyToken && _path.length >= 2 ); // execute swaps on behalf of trader _output = _swap.input; for(uint i = 1; i < _path.length; i++){ _output = doDistributedSwap(SwapParams({ sellToken : _path[i - 1], input : _output, // output of last swap is input for this one buyToken : _path[i], minOutput : 0 // we check the total outcome in the end }), _distribution[i - 1]); } // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to sender send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } // internal function to perform a distributed swap function doDistributedSwap( SwapParams memory _swap, DistributionParams memory _distribution ) internal returns(uint){ // count totalChunks uint totalChunks = 0; for(uint i = 0; i < _distribution.chunks.length; i++){ totalChunks += _distribution.chunks[i]; } // route trades to the different exchanges for(uint i = 0; i < _distribution.exchangeModules.length; i++){ IAtomicExchange exchange = _distribution.exchangeModules[i]; uint thisInput = _swap.input * _distribution.chunks[i] / totalChunks; if(address(exchange) == address(0)){ // trade is not using an exchange module but a direct call (address target, uint value, bytes memory callData) = abi.decode(_distribution.exchangeData[i], (address, uint, bytes)); (bool success, bytes memory data) = address(target).call.value(value)(callData); require(success, "Exchange call reverted."); }else{ // delegate call to the exchange module (bool success, bytes memory data) = address(exchange).delegatecall( abi.encodePacked(// This encodes the function to call and the parameters we are passing to the settlement function exchange.swap.selector, abi.encode( SwapParams({ sellToken : _swap.sellToken, input : thisInput, buyToken : _swap.buyToken, minOutput : 1 // we are checking the combined output in the end }), _distribution.exchangeData[i] ) ) ); require(success, "Exchange module reverted."); } } return balanceOf(_swap.buyToken); } // perform a distributed swap function swap( SwapParams memory _swap, DistributionParams memory _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a multi-path distributed swap function multiPathSwap( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // allow ETH receivals receive() external payable {} }
swapAndSend
function swapAndSend( SwapParams memory _swap, DistributionParams memory _distribution, address payable _receipient ) public payable returns (uint _output){ // execute swaps on behalf of trader _output = doDistributedSwap(_swap, _distribution); // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to receipient send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); }
// IMPORTANT NOTICE: // NEVER set a token allowance to this contract, as everybody can do arbitrary calls from it. // When swapping tokens always go through AtomicTokenProxy. // This contract assumes token to swap has already been transfered to it when being called. Ether can be sent directly with the call. // perform a distributed swap and transfer outcome to _receipient
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 452, 1236 ] }
4,954
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicBlue
contract AtomicBlue is AtomicUtils, AtomicTypes{ // IMPORTANT NOTICE: // NEVER set a token allowance to this contract, as everybody can do arbitrary calls from it. // When swapping tokens always go through AtomicTokenProxy. // This contract assumes token to swap has already been transfered to it when being called. Ether can be sent directly with the call. // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams memory _swap, DistributionParams memory _distribution, address payable _receipient ) public payable returns (uint _output){ // execute swaps on behalf of trader _output = doDistributedSwap(_swap, _distribution); // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to receipient send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } function multiPathSwapAndSend( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution, address payable _receipient ) public payable returns (uint _output){ // verify path require( _path[0] == _swap.sellToken && _path[_path.length - 1] == _swap.buyToken && _path.length >= 2 ); // execute swaps on behalf of trader _output = _swap.input; for(uint i = 1; i < _path.length; i++){ _output = doDistributedSwap(SwapParams({ sellToken : _path[i - 1], input : _output, // output of last swap is input for this one buyToken : _path[i], minOutput : 0 // we check the total outcome in the end }), _distribution[i - 1]); } // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to sender send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } // internal function to perform a distributed swap function doDistributedSwap( SwapParams memory _swap, DistributionParams memory _distribution ) internal returns(uint){ // count totalChunks uint totalChunks = 0; for(uint i = 0; i < _distribution.chunks.length; i++){ totalChunks += _distribution.chunks[i]; } // route trades to the different exchanges for(uint i = 0; i < _distribution.exchangeModules.length; i++){ IAtomicExchange exchange = _distribution.exchangeModules[i]; uint thisInput = _swap.input * _distribution.chunks[i] / totalChunks; if(address(exchange) == address(0)){ // trade is not using an exchange module but a direct call (address target, uint value, bytes memory callData) = abi.decode(_distribution.exchangeData[i], (address, uint, bytes)); (bool success, bytes memory data) = address(target).call.value(value)(callData); require(success, "Exchange call reverted."); }else{ // delegate call to the exchange module (bool success, bytes memory data) = address(exchange).delegatecall( abi.encodePacked(// This encodes the function to call and the parameters we are passing to the settlement function exchange.swap.selector, abi.encode( SwapParams({ sellToken : _swap.sellToken, input : thisInput, buyToken : _swap.buyToken, minOutput : 1 // we are checking the combined output in the end }), _distribution.exchangeData[i] ) ) ); require(success, "Exchange module reverted."); } } return balanceOf(_swap.buyToken); } // perform a distributed swap function swap( SwapParams memory _swap, DistributionParams memory _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a multi-path distributed swap function multiPathSwap( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // allow ETH receivals receive() external payable {} }
doDistributedSwap
function doDistributedSwap( SwapParams memory _swap, DistributionParams memory _distribution ) internal returns(uint){ // count totalChunks uint totalChunks = 0; for(uint i = 0; i < _distribution.chunks.length; i++){ totalChunks += _distribution.chunks[i]; } // route trades to the different exchanges for(uint i = 0; i < _distribution.exchangeModules.length; i++){ IAtomicExchange exchange = _distribution.exchangeModules[i]; uint thisInput = _swap.input * _distribution.chunks[i] / totalChunks; if(address(exchange) == address(0)){ // trade is not using an exchange module but a direct call (address target, uint value, bytes memory callData) = abi.decode(_distribution.exchangeData[i], (address, uint, bytes)); (bool success, bytes memory data) = address(target).call.value(value)(callData); require(success, "Exchange call reverted."); }else{ // delegate call to the exchange module (bool success, bytes memory data) = address(exchange).delegatecall( abi.encodePacked(// This encodes the function to call and the parameters we are passing to the settlement function exchange.swap.selector, abi.encode( SwapParams({ sellToken : _swap.sellToken, input : thisInput, buyToken : _swap.buyToken, minOutput : 1 // we are checking the combined output in the end }), _distribution.exchangeData[i] ) ) ); require(success, "Exchange module reverted."); } } return balanceOf(_swap.buyToken); }
// internal function to perform a distributed swap
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 2722, 4885 ] }
4,955
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicBlue
contract AtomicBlue is AtomicUtils, AtomicTypes{ // IMPORTANT NOTICE: // NEVER set a token allowance to this contract, as everybody can do arbitrary calls from it. // When swapping tokens always go through AtomicTokenProxy. // This contract assumes token to swap has already been transfered to it when being called. Ether can be sent directly with the call. // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams memory _swap, DistributionParams memory _distribution, address payable _receipient ) public payable returns (uint _output){ // execute swaps on behalf of trader _output = doDistributedSwap(_swap, _distribution); // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to receipient send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } function multiPathSwapAndSend( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution, address payable _receipient ) public payable returns (uint _output){ // verify path require( _path[0] == _swap.sellToken && _path[_path.length - 1] == _swap.buyToken && _path.length >= 2 ); // execute swaps on behalf of trader _output = _swap.input; for(uint i = 1; i < _path.length; i++){ _output = doDistributedSwap(SwapParams({ sellToken : _path[i - 1], input : _output, // output of last swap is input for this one buyToken : _path[i], minOutput : 0 // we check the total outcome in the end }), _distribution[i - 1]); } // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to sender send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } // internal function to perform a distributed swap function doDistributedSwap( SwapParams memory _swap, DistributionParams memory _distribution ) internal returns(uint){ // count totalChunks uint totalChunks = 0; for(uint i = 0; i < _distribution.chunks.length; i++){ totalChunks += _distribution.chunks[i]; } // route trades to the different exchanges for(uint i = 0; i < _distribution.exchangeModules.length; i++){ IAtomicExchange exchange = _distribution.exchangeModules[i]; uint thisInput = _swap.input * _distribution.chunks[i] / totalChunks; if(address(exchange) == address(0)){ // trade is not using an exchange module but a direct call (address target, uint value, bytes memory callData) = abi.decode(_distribution.exchangeData[i], (address, uint, bytes)); (bool success, bytes memory data) = address(target).call.value(value)(callData); require(success, "Exchange call reverted."); }else{ // delegate call to the exchange module (bool success, bytes memory data) = address(exchange).delegatecall( abi.encodePacked(// This encodes the function to call and the parameters we are passing to the settlement function exchange.swap.selector, abi.encode( SwapParams({ sellToken : _swap.sellToken, input : thisInput, buyToken : _swap.buyToken, minOutput : 1 // we are checking the combined output in the end }), _distribution.exchangeData[i] ) ) ); require(success, "Exchange module reverted."); } } return balanceOf(_swap.buyToken); } // perform a distributed swap function swap( SwapParams memory _swap, DistributionParams memory _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a multi-path distributed swap function multiPathSwap( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // allow ETH receivals receive() external payable {} }
swap
function swap( SwapParams memory _swap, DistributionParams memory _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); }
// perform a distributed swap
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 4927, 5145 ] }
4,956
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicBlue
contract AtomicBlue is AtomicUtils, AtomicTypes{ // IMPORTANT NOTICE: // NEVER set a token allowance to this contract, as everybody can do arbitrary calls from it. // When swapping tokens always go through AtomicTokenProxy. // This contract assumes token to swap has already been transfered to it when being called. Ether can be sent directly with the call. // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams memory _swap, DistributionParams memory _distribution, address payable _receipient ) public payable returns (uint _output){ // execute swaps on behalf of trader _output = doDistributedSwap(_swap, _distribution); // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to receipient send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } function multiPathSwapAndSend( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution, address payable _receipient ) public payable returns (uint _output){ // verify path require( _path[0] == _swap.sellToken && _path[_path.length - 1] == _swap.buyToken && _path.length >= 2 ); // execute swaps on behalf of trader _output = _swap.input; for(uint i = 1; i < _path.length; i++){ _output = doDistributedSwap(SwapParams({ sellToken : _path[i - 1], input : _output, // output of last swap is input for this one buyToken : _path[i], minOutput : 0 // we check the total outcome in the end }), _distribution[i - 1]); } // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to sender send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } // internal function to perform a distributed swap function doDistributedSwap( SwapParams memory _swap, DistributionParams memory _distribution ) internal returns(uint){ // count totalChunks uint totalChunks = 0; for(uint i = 0; i < _distribution.chunks.length; i++){ totalChunks += _distribution.chunks[i]; } // route trades to the different exchanges for(uint i = 0; i < _distribution.exchangeModules.length; i++){ IAtomicExchange exchange = _distribution.exchangeModules[i]; uint thisInput = _swap.input * _distribution.chunks[i] / totalChunks; if(address(exchange) == address(0)){ // trade is not using an exchange module but a direct call (address target, uint value, bytes memory callData) = abi.decode(_distribution.exchangeData[i], (address, uint, bytes)); (bool success, bytes memory data) = address(target).call.value(value)(callData); require(success, "Exchange call reverted."); }else{ // delegate call to the exchange module (bool success, bytes memory data) = address(exchange).delegatecall( abi.encodePacked(// This encodes the function to call and the parameters we are passing to the settlement function exchange.swap.selector, abi.encode( SwapParams({ sellToken : _swap.sellToken, input : thisInput, buyToken : _swap.buyToken, minOutput : 1 // we are checking the combined output in the end }), _distribution.exchangeData[i] ) ) ); require(success, "Exchange module reverted."); } } return balanceOf(_swap.buyToken); } // perform a distributed swap function swap( SwapParams memory _swap, DistributionParams memory _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a multi-path distributed swap function multiPathSwap( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // allow ETH receivals receive() external payable {} }
multiPathSwap
function multiPathSwap( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); }
// perform a multi-path distributed swap
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 5198, 5476 ] }
4,957
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicBlue
contract AtomicBlue is AtomicUtils, AtomicTypes{ // IMPORTANT NOTICE: // NEVER set a token allowance to this contract, as everybody can do arbitrary calls from it. // When swapping tokens always go through AtomicTokenProxy. // This contract assumes token to swap has already been transfered to it when being called. Ether can be sent directly with the call. // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams memory _swap, DistributionParams memory _distribution, address payable _receipient ) public payable returns (uint _output){ // execute swaps on behalf of trader _output = doDistributedSwap(_swap, _distribution); // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to receipient send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } function multiPathSwapAndSend( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution, address payable _receipient ) public payable returns (uint _output){ // verify path require( _path[0] == _swap.sellToken && _path[_path.length - 1] == _swap.buyToken && _path.length >= 2 ); // execute swaps on behalf of trader _output = _swap.input; for(uint i = 1; i < _path.length; i++){ _output = doDistributedSwap(SwapParams({ sellToken : _path[i - 1], input : _output, // output of last swap is input for this one buyToken : _path[i], minOutput : 0 // we check the total outcome in the end }), _distribution[i - 1]); } // check if output of swap is sufficient require(_output >= _swap.minOutput, "Slippage limit exceeded."); // send swap output to sender send(_swap.buyToken, _receipient, _output); emit Trade( address(_swap.sellToken), _swap.input, address(_swap.buyToken), _output, msg.sender, _receipient ); } // internal function to perform a distributed swap function doDistributedSwap( SwapParams memory _swap, DistributionParams memory _distribution ) internal returns(uint){ // count totalChunks uint totalChunks = 0; for(uint i = 0; i < _distribution.chunks.length; i++){ totalChunks += _distribution.chunks[i]; } // route trades to the different exchanges for(uint i = 0; i < _distribution.exchangeModules.length; i++){ IAtomicExchange exchange = _distribution.exchangeModules[i]; uint thisInput = _swap.input * _distribution.chunks[i] / totalChunks; if(address(exchange) == address(0)){ // trade is not using an exchange module but a direct call (address target, uint value, bytes memory callData) = abi.decode(_distribution.exchangeData[i], (address, uint, bytes)); (bool success, bytes memory data) = address(target).call.value(value)(callData); require(success, "Exchange call reverted."); }else{ // delegate call to the exchange module (bool success, bytes memory data) = address(exchange).delegatecall( abi.encodePacked(// This encodes the function to call and the parameters we are passing to the settlement function exchange.swap.selector, abi.encode( SwapParams({ sellToken : _swap.sellToken, input : thisInput, buyToken : _swap.buyToken, minOutput : 1 // we are checking the combined output in the end }), _distribution.exchangeData[i] ) ) ); require(success, "Exchange module reverted."); } } return balanceOf(_swap.buyToken); } // perform a distributed swap function swap( SwapParams memory _swap, DistributionParams memory _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a multi-path distributed swap function multiPathSwap( SwapParams memory _swap, Token[] calldata _path, DistributionParams[] memory _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // allow ETH receivals receive() external payable {} }
// allow ETH receivals
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 5507, 5541 ] }
4,958
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicTokenProxy
contract AtomicTokenProxy is AtomicUtils, AtomicTypes{ AtomicBlue constant atomic = AtomicBlue(0xeb5DF44d56B0d4cCd63734A99881B2F3f002ECC2); // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); } // perform a multi-path distributed swap and transfer outcome to _receipient function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); } // perform a distributed swap function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a distributed swap and burn optimal gastoken amount afterwards function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // perform a multi-path distributed swap and burn optimal gastoken amount afterwards function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } }
swapAndSend
function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); }
// perform a distributed swap and transfer outcome to _receipient
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 219, 709 ] }
4,959
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicTokenProxy
contract AtomicTokenProxy is AtomicUtils, AtomicTypes{ AtomicBlue constant atomic = AtomicBlue(0xeb5DF44d56B0d4cCd63734A99881B2F3f002ECC2); // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); } // perform a multi-path distributed swap and transfer outcome to _receipient function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); } // perform a distributed swap function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a distributed swap and burn optimal gastoken amount afterwards function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // perform a multi-path distributed swap and burn optimal gastoken amount afterwards function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } }
multiPathSwapAndSend
function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); }
// perform a multi-path distributed swap and transfer outcome to _receipient
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 798, 1421 ] }
4,960
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicTokenProxy
contract AtomicTokenProxy is AtomicUtils, AtomicTypes{ AtomicBlue constant atomic = AtomicBlue(0xeb5DF44d56B0d4cCd63734A99881B2F3f002ECC2); // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); } // perform a multi-path distributed swap and transfer outcome to _receipient function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); } // perform a distributed swap function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a distributed swap and burn optimal gastoken amount afterwards function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // perform a multi-path distributed swap and burn optimal gastoken amount afterwards function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } }
swap
function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); }
// perform a distributed swap
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 1463, 1685 ] }
4,961
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicTokenProxy
contract AtomicTokenProxy is AtomicUtils, AtomicTypes{ AtomicBlue constant atomic = AtomicBlue(0xeb5DF44d56B0d4cCd63734A99881B2F3f002ECC2); // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); } // perform a multi-path distributed swap and transfer outcome to _receipient function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); } // perform a distributed swap function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a distributed swap and burn optimal gastoken amount afterwards function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // perform a multi-path distributed swap and burn optimal gastoken amount afterwards function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } }
swapWithGasTokens
function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); }
// perform a distributed swap and burn optimal gastoken amount afterwards
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 1771, 2201 ] }
4,962
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicTokenProxy
contract AtomicTokenProxy is AtomicUtils, AtomicTypes{ AtomicBlue constant atomic = AtomicBlue(0xeb5DF44d56B0d4cCd63734A99881B2F3f002ECC2); // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); } // perform a multi-path distributed swap and transfer outcome to _receipient function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); } // perform a distributed swap function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a distributed swap and burn optimal gastoken amount afterwards function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // perform a multi-path distributed swap and burn optimal gastoken amount afterwards function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } }
multiPathSwap
function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); }
// perform a multi-path distributed swap
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 2254, 2536 ] }
4,963
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicTokenProxy
contract AtomicTokenProxy is AtomicUtils, AtomicTypes{ AtomicBlue constant atomic = AtomicBlue(0xeb5DF44d56B0d4cCd63734A99881B2F3f002ECC2); // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); } // perform a multi-path distributed swap and transfer outcome to _receipient function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); } // perform a distributed swap function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a distributed swap and burn optimal gastoken amount afterwards function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // perform a multi-path distributed swap and burn optimal gastoken amount afterwards function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } }
multiPathSwapWithGasTokens
function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); }
// perform a multi-path distributed swap and burn optimal gastoken amount afterwards
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 2633, 3123 ] }
4,964
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicTokenProxy
contract AtomicTokenProxy is AtomicUtils, AtomicTypes{ AtomicBlue constant atomic = AtomicBlue(0xeb5DF44d56B0d4cCd63734A99881B2F3f002ECC2); // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); } // perform a multi-path distributed swap and transfer outcome to _receipient function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); } // perform a distributed swap function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a distributed swap and burn optimal gastoken amount afterwards function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // perform a multi-path distributed swap and burn optimal gastoken amount afterwards function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } }
swapAndSendWithGasTokens
function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); }
// perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 3238, 3714 ] }
4,965
AtomicTokenProxy
AtomicTokenProxy.sol
0x197ad54648338ff265235c28fda966a637b13c63
Solidity
AtomicTokenProxy
contract AtomicTokenProxy is AtomicUtils, AtomicTypes{ AtomicBlue constant atomic = AtomicBlue(0xeb5DF44d56B0d4cCd63734A99881B2F3f002ECC2); // perform a distributed swap and transfer outcome to _receipient function swapAndSend( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.swapAndSend.value(msg.value)(_swap, _distribution, _receipient); } // perform a multi-path distributed swap and transfer outcome to _receipient function multiPathSwapAndSend( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient ) public payable returns (uint _output){ // deposit tokens to executor claimTokenFromSenderTo(_swap.sellToken, _swap.input, address(atomic)); // execute swaps on behalf of sender _output = atomic.multiPathSwapAndSend.value(msg.value)( _swap, _path, _distribution, _receipient ); } // perform a distributed swap function swap( SwapParams calldata _swap, DistributionParams calldata _distribution ) public payable returns (uint _output){ return swapAndSend(_swap, _distribution, msg.sender); } // perform a distributed swap and burn optimal gastoken amount afterwards function swapWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap function multiPathSwap( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution ) public payable returns (uint _output){ return multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); } // perform a multi-path distributed swap and burn optimal gastoken amount afterwards function multiPathSwapWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, msg.sender); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function swapAndSendWithGasTokens( SwapParams calldata _swap, DistributionParams calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = swapAndSend(_swap, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } // perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); } }
multiPathSwapAndSendWithGasTokens
function multiPathSwapAndSendWithGasTokens( SwapParams calldata _swap, Token[] calldata _path, DistributionParams[] calldata _distribution, address payable _receipient, IGasToken _gasToken, uint _gasQtyPerToken ) public payable returns (uint _output){ uint startGas = gasleft(); _output = multiPathSwapAndSend(_swap, _path, _distribution, _receipient); _gasToken.freeFromUpTo(msg.sender, (startGas - gasleft() + 25000) / _gasQtyPerToken); }
// perform a multi-path distributed swap, send outcome to _receipient and burn optimal gastoken amount afterwards
LineComment
v0.6.12+commit.27d51765
None
ipfs://ca01bb6266925b6945b275a49f3f5f70c51cf4baf0e60829dfbf165e99e69210
{ "func_code_index": [ 3840, 4376 ] }
4,966
Warsnails
contracts/Warsnails.sol
0x3c197a9bbedccd44d71f4dd8581bbf6a7196c57d
Solidity
Warsnails
contract Warsnails is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; string public baseURI; string public extension = ".json"; uint256 public cost = 0.08 ether; uint256 public presaleCost = 0.06 ether; uint256 public maxSnails = 8888; uint256 public teamAlloctation = 445; uint256 public teamCount = 0; uint256 public presaleCap = 250; uint256 public maxMintAmount = 100; uint256 public maxMintAmountPresale = 5; bool public pausedMint = true; bool public endpresale = false; bool public revealed = false; string public notRevealedUri; address[] public whitelistusers; mapping(address=>uint256) public isMint; constructor( string memory _name, string memory _symbol, string memory _initURI, string memory _notRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initURI); setNotRevealedURI(_notRevealedUri); } function whitelistAddresses(address[] calldata _whitelistusers) external onlyOwner { delete whitelistusers; whitelistusers = _whitelistusers; } function addressesTotal() external view returns(uint256) { return whitelistusers.length; } /** * @dev function to mint presale snails * * - function checks teams allocation */ function mintSnailsPresale(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); if (msg.sender == owner()) { teamCount += _mintAmount; require(teamCount <= teamAlloctation, "teamAlloctation cap reached!"); require(supply.add(_mintAmount) <= maxSnails, "Max supply reached!"); }else { require(!endpresale, "Presale ended"); require(isMaxMintPresale(msg.sender) == false, "Presale user max mint reached!"); require(isWhitelisted(msg.sender), "Not whitelisted"); require(_mintAmount > 0, "Mint amount cannot be 0"); require(_mintAmount <= maxMintAmountPresale, "Max Mint amount reached!"); require(supply.add(_mintAmount) <= presaleCap, "Presale cap reached!"); require(msg.value >= presaleCost.mul(_mintAmount), "Insufficient ether"); isMint[msg.sender] += _mintAmount; } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function mintSnails(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!pausedMint, "Mint paused!"); require(_mintAmount > 0, "Mint amount cannot be 0"); require(_mintAmount <= maxMintAmount, "Max Mint amount reached!"); require(supply.add(_mintAmount) <= maxSnails, "Max supply reached!"); require(msg.value >= cost.mul(_mintAmount), "Insufficient ether"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), extension)) : ""; } function reveal() public onlyOwner { revealed = true; } function updatePresaleCost(uint256 _newCost) public onlyOwner { presaleCost = _newCost; } function updateCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function pausemint(bool _state) public onlyOwner { pausedMint = _state; } /** * @dev function to update presalecap * * - Snail presale can be up to 5 waves */ function updatePresaleCap(uint256 _newCap) public onlyOwner { presaleCap = _newCap; } function updatemaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function updatemaxPresaleMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmountPresale = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function updateBaseExtension(string memory _newUriExtension) public onlyOwner { extension = _newUriExtension; } function endPresale(bool _state) public onlyOwner { endpresale = _state; } function isMaxMintPresale(address _user) public view returns(bool) { return isMint[_user] >= maxMintAmountPresale; } function isWhitelisted(address _user) public view returns(bool) { for (uint256 x =0; x < whitelistusers.length; x++) { if (whitelistusers[x] == _user) { return true; } } return false; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value:address(this).balance}(""); require(success); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } }
mintSnailsPresale
function mintSnailsPresale(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); if (msg.sender == owner()) { teamCount += _mintAmount; require(teamCount <= teamAlloctation, "teamAlloctation cap reached!"); require(supply.add(_mintAmount) <= maxSnails, "Max supply reached!"); }else { require(!endpresale, "Presale ended"); require(isMaxMintPresale(msg.sender) == false, "Presale user max mint reached!"); require(isWhitelisted(msg.sender), "Not whitelisted"); require(_mintAmount > 0, "Mint amount cannot be 0"); require(_mintAmount <= maxMintAmountPresale, "Max Mint amount reached!"); require(supply.add(_mintAmount) <= presaleCap, "Presale cap reached!"); require(msg.value >= presaleCost.mul(_mintAmount), "Insufficient ether"); isMint[msg.sender] += _mintAmount; } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } }
/** * @dev function to mint presale snails * * - function checks teams allocation */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://965e4270ffb99672fc47ec19c80866d92c5b2b82ed007c03d36b5238214c5afa
{ "func_code_index": [ 1480, 2612 ] }
4,967
Warsnails
contracts/Warsnails.sol
0x3c197a9bbedccd44d71f4dd8581bbf6a7196c57d
Solidity
Warsnails
contract Warsnails is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; string public baseURI; string public extension = ".json"; uint256 public cost = 0.08 ether; uint256 public presaleCost = 0.06 ether; uint256 public maxSnails = 8888; uint256 public teamAlloctation = 445; uint256 public teamCount = 0; uint256 public presaleCap = 250; uint256 public maxMintAmount = 100; uint256 public maxMintAmountPresale = 5; bool public pausedMint = true; bool public endpresale = false; bool public revealed = false; string public notRevealedUri; address[] public whitelistusers; mapping(address=>uint256) public isMint; constructor( string memory _name, string memory _symbol, string memory _initURI, string memory _notRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initURI); setNotRevealedURI(_notRevealedUri); } function whitelistAddresses(address[] calldata _whitelistusers) external onlyOwner { delete whitelistusers; whitelistusers = _whitelistusers; } function addressesTotal() external view returns(uint256) { return whitelistusers.length; } /** * @dev function to mint presale snails * * - function checks teams allocation */ function mintSnailsPresale(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); if (msg.sender == owner()) { teamCount += _mintAmount; require(teamCount <= teamAlloctation, "teamAlloctation cap reached!"); require(supply.add(_mintAmount) <= maxSnails, "Max supply reached!"); }else { require(!endpresale, "Presale ended"); require(isMaxMintPresale(msg.sender) == false, "Presale user max mint reached!"); require(isWhitelisted(msg.sender), "Not whitelisted"); require(_mintAmount > 0, "Mint amount cannot be 0"); require(_mintAmount <= maxMintAmountPresale, "Max Mint amount reached!"); require(supply.add(_mintAmount) <= presaleCap, "Presale cap reached!"); require(msg.value >= presaleCost.mul(_mintAmount), "Insufficient ether"); isMint[msg.sender] += _mintAmount; } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function mintSnails(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!pausedMint, "Mint paused!"); require(_mintAmount > 0, "Mint amount cannot be 0"); require(_mintAmount <= maxMintAmount, "Max Mint amount reached!"); require(supply.add(_mintAmount) <= maxSnails, "Max supply reached!"); require(msg.value >= cost.mul(_mintAmount), "Insufficient ether"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), extension)) : ""; } function reveal() public onlyOwner { revealed = true; } function updatePresaleCost(uint256 _newCost) public onlyOwner { presaleCost = _newCost; } function updateCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function pausemint(bool _state) public onlyOwner { pausedMint = _state; } /** * @dev function to update presalecap * * - Snail presale can be up to 5 waves */ function updatePresaleCap(uint256 _newCap) public onlyOwner { presaleCap = _newCap; } function updatemaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function updatemaxPresaleMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmountPresale = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function updateBaseExtension(string memory _newUriExtension) public onlyOwner { extension = _newUriExtension; } function endPresale(bool _state) public onlyOwner { endpresale = _state; } function isMaxMintPresale(address _user) public view returns(bool) { return isMint[_user] >= maxMintAmountPresale; } function isWhitelisted(address _user) public view returns(bool) { for (uint256 x =0; x < whitelistusers.length; x++) { if (whitelistusers[x] == _user) { return true; } } return false; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value:address(this).balance}(""); require(success); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } }
updatePresaleCap
function updatePresaleCap(uint256 _newCap) public onlyOwner { presaleCap = _newCap; }
/** * @dev function to update presalecap * * - Snail presale can be up to 5 waves */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://965e4270ffb99672fc47ec19c80866d92c5b2b82ed007c03d36b5238214c5afa
{ "func_code_index": [ 4323, 4431 ] }
4,968
DiscCoin
DiscCoin.sol
0x3e318c580d23c28156fe0da55ad71b41798b75ed
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://dc8b7a5a75d96119aab014a689b92b1af3d0293899c693e36bcae95564213c91
{ "func_code_index": [ 60, 124 ] }
4,969
DiscCoin
DiscCoin.sol
0x3e318c580d23c28156fe0da55ad71b41798b75ed
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://dc8b7a5a75d96119aab014a689b92b1af3d0293899c693e36bcae95564213c91
{ "func_code_index": [ 232, 309 ] }
4,970
DiscCoin
DiscCoin.sol
0x3e318c580d23c28156fe0da55ad71b41798b75ed
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://dc8b7a5a75d96119aab014a689b92b1af3d0293899c693e36bcae95564213c91
{ "func_code_index": [ 546, 623 ] }
4,971
DiscCoin
DiscCoin.sol
0x3e318c580d23c28156fe0da55ad71b41798b75ed
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://dc8b7a5a75d96119aab014a689b92b1af3d0293899c693e36bcae95564213c91
{ "func_code_index": [ 946, 1042 ] }
4,972
DiscCoin
DiscCoin.sol
0x3e318c580d23c28156fe0da55ad71b41798b75ed
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://dc8b7a5a75d96119aab014a689b92b1af3d0293899c693e36bcae95564213c91
{ "func_code_index": [ 1326, 1407 ] }
4,973
DiscCoin
DiscCoin.sol
0x3e318c580d23c28156fe0da55ad71b41798b75ed
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
/// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://dc8b7a5a75d96119aab014a689b92b1af3d0293899c693e36bcae95564213c91
{ "func_code_index": [ 1615, 1712 ] }
4,974
DiscCoin
DiscCoin.sol
0x3e318c580d23c28156fe0da55ad71b41798b75ed
Solidity
DiscCoin
contract DiscCoin is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function DiscCoin() { balances[msg.sender] = 58980000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 58980000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "DISCCOIN"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "DISC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 10000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
DiscCoin
function DiscCoin() { balances[msg.sender] = 58980000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 58980000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "DISCCOIN"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "DISC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 10000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH }
// Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above
LineComment
v0.4.19+commit.c4cbbb05
bzzr://dc8b7a5a75d96119aab014a689b92b1af3d0293899c693e36bcae95564213c91
{ "func_code_index": [ 1196, 2214 ] }
4,975
DiscCoin
DiscCoin.sol
0x3e318c580d23c28156fe0da55ad71b41798b75ed
Solidity
DiscCoin
contract DiscCoin is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function DiscCoin() { balances[msg.sender] = 58980000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 58980000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "DISCCOIN"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "DISC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 10000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; }
/* Approves and then calls the receiving contract */
Comment
v0.4.19+commit.c4cbbb05
bzzr://dc8b7a5a75d96119aab014a689b92b1af3d0293899c693e36bcae95564213c91
{ "func_code_index": [ 2838, 3643 ] }
4,976
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
approve
function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); }
/** * @dev See {IERC721-approve}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 3667, 4070 ] }
4,977
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
getApproved
function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; }
/** * @dev See {IERC721-getApproved}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 4127, 4348 ] }
4,978
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); }
/** * @dev See {IERC721-setApprovalForAll}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 4411, 4568 ] }
4,979
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; }
/** * @dev See {IERC721-isApprovedForAll}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 4630, 4796 ] }
4,980
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
transferFrom
function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); }
/** * @dev See {IERC721-transferFrom}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 4854, 5188 ] }
4,981
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 5250, 5433 ] }
4,982
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 5495, 5819 ] }
4,983
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_safeTransfer
function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); }
/** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 6677, 6988 ] }
4,984
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_exists
function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); }
/** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 7287, 7416 ] }
4,985
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_isApprovedOrOwner
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); }
/** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 7570, 7916 ] }
4,986
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_safeMint
function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); }
/** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 8242, 8354 ] }
4,987
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_safeMint
function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); }
/** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 8571, 8886 ] }
4,988
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_mint
function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); }
/** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 9204, 9580 ] }
4,989
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_transfer
function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); }
/** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 9901, 10462 ] }
4,990
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_approve
function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); }
/** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 10569, 10742 ] }
4,991
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_setApprovalForAll
function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); }
/** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 10873, 11184 ] }
4,992
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_checkOnERC721Received
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } }
/** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 11733, 12515 ] }
4,993
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
_beforeTokenTransfer
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {}
/** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 13067, 13193 ] }
4,994
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 13254, 13494 ] }
4,995
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
balanceOf
function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; }
/** * @dev See {IERC721-balanceOf}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 13549, 13758 ] }
4,996
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
ownerOf
function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; }
/** * @dev See {IERC721-ownerOf}. */
NatSpecMultiLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 13811, 14050 ] }
4,997
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
random
function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); }
///////////////////// //// BYOT ///////////// //////////////////////
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 14137, 14277 ] }
4,998
BYOT
BYOT.sol
0x49789d0b0f73b9195d72d94979320a33530aea94
Solidity
BYOT
contract BYOT is Context, ERC165, IERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 numFreeMinted = 0; uint256 numPurchased = 0; uint256 totalSupply = 2500; uint256 freeSupply = 500; // Mapping from token ID to owner address mapping(address => uint256) public mintCredits; uint MINT_PRICE = .04 ether; string[] private hourNums = [ "1","2","3","4","5","6","7","8","9","10","11","12" ]; // 0 AM 1 PM uint[] private timeSuffixes = [ 0, 1 ]; string[] private months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; string[] private activities = [ "Crying","Buying the dip","Panic selling","Buying high, selling low", "Watching Jack Dorsey and a16z roast each other","Hodling", "Selling all my fiat","Thinking about moving to Miami", "Getting rekt","Keeping up with the Kardashians", "Changing my pfp","Channeling Pete Davidson energy", "Petting Doge", "Serenading the Queen of England", "Simping to Drake songs","Figuring out what's in Subway's tuna sandwich", "Eating a big ass can of beans","Giving Satan a lap dance", "Hitting a blunt with Joe Rogan","Getting into a Twitter fight over Chik-fil-a vs. Popeyes", "Getting a pedicure with Elizabeth Warren","On a first date", "Buying the constitution","Throwing up on Ken Griffin's shirt", "Quitting my job", "Arguing with a Bitcoin maxi", "Getting a colonoscopy", "Arm wrestling The Rock", "Shitposting", "Waiting on gas fees to go down", "Raising a $100M seed round","Getting wasted" ]; string[] private outfits = [ "My birthday suit", "A Spiderman costume", "Socks and sandals", "Crocs", "Harry Potter's invisibility cloak", "Steve Job's turtleneck", "A grey Patagonia vest", "An Oculus headset","Hella sunscreen", "Yeezys","Dora's backpack","Bernie Sander's mittens", "Timberland boots","A panda onesie","Wolf of Wall Street's suit", "A Supreme Hoodie","A Speedo", "Jake from State Farm's sweater", "A Gucci belt", "A Ski mask" ]; string[] private locations = [ "On the moon","At karaoke with Voldemort","In the metaverse", "On the toilet", "At Olive Garden","In a Prius with Elon Musk", "In a pineapple under the sea","In my parents' basement", "In Snoop Dogg's mansion","At the SEC Chairman's house", "In Scooby Doo's van","On stage at a comedy club", "On the subway","In line at TSA","On Lil Yachty's Yacht", "At the Grammys","At the Crypto.com Arena","At Times Square", "In a billionaire's spaceship","At a funeral home", "At a nursing home's Bingo Night","At a Justin Bieber concert", "In the 4th dimension","In a Geico commercial" ]; string[] private rarities = [ "Leap Year", "End of the World", "420 B.C.", "42069 A.D.", "1787", "The Big Bang" ]; // ERC 721 /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = BYOT.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = BYOT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(BYOT.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(BYOT.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } ///////////////////// //// BYOT ///////////// ////////////////////// function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getMinutes(uint256 tokenId) public pure returns (string memory) { uint256 rand = random(string(abi.encodePacked("MINUTES", toString(tokenId)))); uint256 minutesNum = rand % 60; if(minutesNum >= 10){ return string(abi.encodePacked("",toString(minutesNum))); } return string(abi.encodePacked("0",toString(minutesNum))); } function getHourNum(uint256 tokenId) internal view returns (uint256) { uint256 rand = random(string(abi.encodePacked("HOURS", toString(tokenId)))); uint256 index = rand % hourNums.length; return index; } function getHours(uint256 tokenId) public view returns (string memory) { uint256 index = getHourNum(tokenId); string memory output = hourNums[index]; return output; } function getTimeSuffixNum(uint256 tokenId) public view returns (uint){ uint256 rand = random(string(abi.encodePacked("SUFFIX", toString(tokenId)))); uint suffix = timeSuffixes[rand % timeSuffixes.length]; return suffix; } function getTimeSuffix(uint256 tokenId) public view returns (string memory) { uint suffix = getTimeSuffixNum(tokenId); if(suffix == 0){ return "AM"; } return "PM"; } function getMonth(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "MONTH", months); } function getActivity(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "ACTIVITY", activities); } function getOutfit(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "OUTFIT", outfits); } function getLocation(uint256 tokenId) public view returns (string memory) { return getTrait(tokenId, "LOCATION", locations); } function getTrait(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns(string memory){ uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function getTimeOfDay(uint256 tokenId) public view returns(string memory) { uint256 hourIndex = getHourNum(tokenId); // index uint timeSuffix = getTimeSuffixNum(tokenId); // 5 - 12pm -- morning 12 - 7pm ge -- otherwise night if(hourIndex >= 4 && hourIndex < 11 && timeSuffix == 0){ return "gm"; } else if((hourIndex == 11 || (hourIndex >=0 && hourIndex < 6)) && timeSuffix == 1){ return "ge"; } return "gn"; } function getTime(uint256 tokenId) public view returns(string memory) { string memory hour = getHours(tokenId); string memory minute = getMinutes(tokenId); return string(abi.encodePacked(hour,":",minute)); } function getRarity(uint256 tokenId) internal pure returns(uint256){ uint256 rand = random(string(abi.encodePacked("RARITY", toString(tokenId)))); uint256 rarity = rand % 120; if(rarity >= 114){ return 1; } return 0; } function getRareTrait(uint256 tokenId) public view returns(string memory) { uint256 rarity = getRarity(tokenId); if(rarity == 0){ return "common"; } else{ return getTrait(tokenId, "RARITY", rarities); } } function tokenURI(uint256 tokenId) public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getTimeOfDay(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getTime(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getTimeSuffix(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getMonth(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getActivity(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getOutfit(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getLocation(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; uint256 rarity = getRarity(tokenId); parts[15] = getRareTrait(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); if(rarity == 0){ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[16])); } else{ output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14],parts[15],parts[16])); } string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "BYOT #', toString(tokenId), '", "description": "Buy Your Own Time (BYOT) is a Loot spin-off from the team at The Infinity Collections. The project combines the concept of Loot with the entertaining, sharable quality of Mad Libs. Mint a BYOT and receive a bizarre scenario depicting what you are doing at a moment in time.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // only owner can withdraw money deposited in the contract function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true; } function mint(uint256 _toMint) public nonReentrant payable { require(_toMint <= 20, "Can only mint a max of 20"); require(numPurchased.add(_toMint) <= totalSupply.sub(freeSupply), "Will exceed alloted supply"); require(msg.value >= (_toMint * MINT_PRICE), "Not enough ether sent"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numPurchased + freeSupply); numPurchased = numPurchased.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function freeMint(uint256 _toMint) public nonReentrant { require(_toMint <= 20, "Can only mint a max of 20"); require(numFreeMinted.add(_toMint) <= freeSupply, "Will exceed alloted free supply"); for(uint256 i = 0; i < _toMint; i++){ _safeMint(_msgSender(),numFreeMinted); numFreeMinted = numFreeMinted.add(1); mintCredits[msg.sender] = mintCredits[msg.sender] + 1; } } function getMintCredits(address _owner) external view returns(uint256){ return mintCredits[_owner]; } function getNumFreeMinted() external view returns(uint256) { return numFreeMinted; } function getNumPurchased() external view returns(uint256) { return numPurchased; } function setPrice(uint256 newPrice) public onlyOwner { MINT_PRICE = newPrice; } function setMaxMint(uint256 newMaxMint) public onlyOwner { totalSupply = newMaxMint; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
withdraw
function withdraw() external onlyOwner returns(bool){ address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); return true;
// only owner can withdraw money deposited in the contract
LineComment
v0.8.0+commit.c7dfd78e
MIT
ipfs://3d2af5faaea75e4440bc37580d0bd820ff1679fff9b93e8bb3bdad01f537d744
{ "func_code_index": [ 20184, 20372 ] }
4,999
PlayerOneToken
PlayerOneToken.sol
0xedf2f194c8d885b3b28098ef8e0b6700a2d95de0
Solidity
PlayerOneToken
contract PlayerOneToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "PLR1"; name = "Player One Token"; decimals = 12; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!isContract(to)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function isContract(address _addr) public view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ----------------------------------------------------------------------------
LineComment
totalSupply
function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.5.12+commit.7709ece9
None
bzzr://2d9b13d046cef584da94e0dd7f45c7c37b0a6b58d61536070c4b09e5beeee8da
{ "func_code_index": [ 939, 1058 ] }
5,000
PlayerOneToken
PlayerOneToken.sol
0xedf2f194c8d885b3b28098ef8e0b6700a2d95de0
Solidity
PlayerOneToken
contract PlayerOneToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "PLR1"; name = "Player One Token"; decimals = 12; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!isContract(to)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function isContract(address _addr) public view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ----------------------------------------------------------------------------
LineComment
balanceOf
function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------
LineComment
v0.5.12+commit.7709ece9
None
bzzr://2d9b13d046cef584da94e0dd7f45c7c37b0a6b58d61536070c4b09e5beeee8da
{ "func_code_index": [ 1280, 1405 ] }
5,001
PlayerOneToken
PlayerOneToken.sol
0xedf2f194c8d885b3b28098ef8e0b6700a2d95de0
Solidity
PlayerOneToken
contract PlayerOneToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "PLR1"; name = "Player One Token"; decimals = 12; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!isContract(to)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function isContract(address _addr) public view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ----------------------------------------------------------------------------
LineComment
transfer
function transfer(address to, uint tokens) public returns (bool success) { require(!isContract(to)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.5.12+commit.7709ece9
None
bzzr://2d9b13d046cef584da94e0dd7f45c7c37b0a6b58d61536070c4b09e5beeee8da
{ "func_code_index": [ 1751, 2058 ] }
5,002
PlayerOneToken
PlayerOneToken.sol
0xedf2f194c8d885b3b28098ef8e0b6700a2d95de0
Solidity
PlayerOneToken
contract PlayerOneToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "PLR1"; name = "Player One Token"; decimals = 12; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!isContract(to)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function isContract(address _addr) public view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ----------------------------------------------------------------------------
LineComment
approve
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------
LineComment
v0.5.12+commit.7709ece9
None
bzzr://2d9b13d046cef584da94e0dd7f45c7c37b0a6b58d61536070c4b09e5beeee8da
{ "func_code_index": [ 2779, 2992 ] }
5,003
PlayerOneToken
PlayerOneToken.sol
0xedf2f194c8d885b3b28098ef8e0b6700a2d95de0
Solidity
PlayerOneToken
contract PlayerOneToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "PLR1"; name = "Player One Token"; decimals = 12; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!isContract(to)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function isContract(address _addr) public view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ----------------------------------------------------------------------------
LineComment
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.5.12+commit.7709ece9
None
bzzr://2d9b13d046cef584da94e0dd7f45c7c37b0a6b58d61536070c4b09e5beeee8da
{ "func_code_index": [ 3530, 3878 ] }
5,004
PlayerOneToken
PlayerOneToken.sol
0xedf2f194c8d885b3b28098ef8e0b6700a2d95de0
Solidity
PlayerOneToken
contract PlayerOneToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "PLR1"; name = "Player One Token"; decimals = 12; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!isContract(to)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function isContract(address _addr) public view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ----------------------------------------------------------------------------
LineComment
allowance
function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------
LineComment
v0.5.12+commit.7709ece9
None
bzzr://2d9b13d046cef584da94e0dd7f45c7c37b0a6b58d61536070c4b09e5beeee8da
{ "func_code_index": [ 4161, 4313 ] }
5,005
PlayerOneToken
PlayerOneToken.sol
0xedf2f194c8d885b3b28098ef8e0b6700a2d95de0
Solidity
PlayerOneToken
contract PlayerOneToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "PLR1"; name = "Player One Token"; decimals = 12; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!isContract(to)); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function isContract(address _addr) public view returns (bool){ uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ----------------------------------------------------------------------------
LineComment
approveAndCall
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------
LineComment
v0.5.12+commit.7709ece9
None
bzzr://2d9b13d046cef584da94e0dd7f45c7c37b0a6b58d61536070c4b09e5beeee8da
{ "func_code_index": [ 4676, 5014 ] }
5,006