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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| /**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
259,
445
]
} | 107 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
723,
864
]
} | 108 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
1162,
1359
]
} | 109 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| /**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
1613,
2089
]
} | 110 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
2560,
2697
]
} | 111 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
3188,
3471
]
} | 112 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
3931,
4066
]
} | 113 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
4546,
4717
]
} | 114 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | Context | abstract contract Context {
//function _msgSender() internal view virtual returns (address payable) {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
} | _msgSender | function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
| //function _msgSender() internal view virtual returns (address payable) { | LineComment | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
108,
211
]
} | 115 |
||
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | isContract | function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
| /**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
606,
1230
]
} | 116 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | sendValue | function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
| /**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
2160,
2562
]
} | 117 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| /**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
3318,
3496
]
} | 118 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
3721,
3922
]
} | 119 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
4292,
4523
]
} | 120 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
4774,
5095
]
} | 121 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | 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 () {
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 = block.timestamp + 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(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
557,
641
]
} | 122 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | 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 () {
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 = block.timestamp + 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(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
1200,
1353
]
} | 123 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | 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 () {
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 = block.timestamp + 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(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
1503,
1752
]
} | 124 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | 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 () {
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 = block.timestamp + 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(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | lock | function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
| //Locks the contract for owner for the amount of time provided | LineComment | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
1920,
2151
]
} | 125 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | 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 () {
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 = block.timestamp + 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(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | unlock | function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
| //Unlocks the contract for owner when _lockTime is exceeds | LineComment | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
2222,
2532
]
} | 126 |
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | BananaKong | contract BananaKong 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;
mapping (address => bool) private botWallets;
bool botscantrade = false;
bool public canTrade = false;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 69000000000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
address public marketingWallet;
string private _name = "Banana Kong";
string private _symbol = "BKONG";
uint8 private _decimals = 9;
uint256 public _taxFee = 1;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 12;
uint256 private _previousLiquidityFee = _liquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 990000000000000000000 * 10**9;
uint256 public numTokensSellToAddToLiquidity = 690000000000000000000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Mainnet & Testnet ETH
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function airdrop(address recipient, uint256 amount) external onlyOwner() {
removeAllFee();
_transfer(_msgSender(), recipient, amount * 10**9);
restoreAllFee();
}
function airdropInternal(address recipient, uint256 amount) internal {
removeAllFee();
_transfer(_msgSender(), recipient, amount);
restoreAllFee();
}
function airdropArray(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner(){
uint256 iterator = 0;
require(newholders.length == amounts.length, "must be the same length");
while(iterator < newholders.length){
airdropInternal(newholders[iterator], amounts[iterator] * 10**9);
iterator += 1;
}
}
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 excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _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);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setMarketingWallet(address walletAddress) public onlyOwner {
marketingWallet = walletAddress;
}
function upliftTxAmount() external onlyOwner() {
_maxTxAmount = 69000000000000000000000 * 10**9;
}
function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() {
require(SwapThresholdAmount > 69000000, "Swap Threshold Amount cannot be less than 69 Million");
numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**9;
}
function claimTokens () public onlyOwner {
// make sure we capture all BNB that may or may not be sent to this contract
payable(marketingWallet).transfer(address(this).balance);
}
function claimOtherTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() {
tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this)));
}
function clearStuckBalance (address payable walletaddress) external onlyOwner() {
walletaddress.transfer(address(this).balance);
}
function addBotWallet(address botwallet) external onlyOwner() {
botWallets[botwallet] = true;
}
function removeBotWallet(address botwallet) external onlyOwner() {
botWallets[botwallet] = false;
}
function getBotWalletStatus(address botwallet) public view returns (bool) {
return botWallets[botwallet];
}
function allowtrading()external onlyOwner() {
canTrade = true;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
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 _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
// add the marketing wallet
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 marketingshare = newBalance.mul(80).div(100);
payable(marketingWallet).transfer(marketingshare);
newBalance -= marketingshare;
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!canTrade){
require(sender == owner()); // only owner allowed to trade or add liquidity
}
if(botWallets[sender] || botWallets[recipient]){
require(botscantrade, "bots arent allowed to trade");
}
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 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_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 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_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 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
} | //to recieve ETH from uniswapV2Router when swaping | LineComment | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
10248,
10282
]
} | 127 |
||||
BananaKong | BananaKong.sol | 0xc2b5fac2dd7ae08d04cc398f7cd2de6ad126bc4d | Solidity | BananaKong | contract BananaKong 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;
mapping (address => bool) private botWallets;
bool botscantrade = false;
bool public canTrade = false;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 69000000000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
address public marketingWallet;
string private _name = "Banana Kong";
string private _symbol = "BKONG";
uint8 private _decimals = 9;
uint256 public _taxFee = 1;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 12;
uint256 private _previousLiquidityFee = _liquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 990000000000000000000 * 10**9;
uint256 public numTokensSellToAddToLiquidity = 690000000000000000000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Mainnet & Testnet ETH
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function airdrop(address recipient, uint256 amount) external onlyOwner() {
removeAllFee();
_transfer(_msgSender(), recipient, amount * 10**9);
restoreAllFee();
}
function airdropInternal(address recipient, uint256 amount) internal {
removeAllFee();
_transfer(_msgSender(), recipient, amount);
restoreAllFee();
}
function airdropArray(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner(){
uint256 iterator = 0;
require(newholders.length == amounts.length, "must be the same length");
while(iterator < newholders.length){
airdropInternal(newholders[iterator], amounts[iterator] * 10**9);
iterator += 1;
}
}
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 excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _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);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setMarketingWallet(address walletAddress) public onlyOwner {
marketingWallet = walletAddress;
}
function upliftTxAmount() external onlyOwner() {
_maxTxAmount = 69000000000000000000000 * 10**9;
}
function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() {
require(SwapThresholdAmount > 69000000, "Swap Threshold Amount cannot be less than 69 Million");
numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**9;
}
function claimTokens () public onlyOwner {
// make sure we capture all BNB that may or may not be sent to this contract
payable(marketingWallet).transfer(address(this).balance);
}
function claimOtherTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() {
tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this)));
}
function clearStuckBalance (address payable walletaddress) external onlyOwner() {
walletaddress.transfer(address(this).balance);
}
function addBotWallet(address botwallet) external onlyOwner() {
botWallets[botwallet] = true;
}
function removeBotWallet(address botwallet) external onlyOwner() {
botWallets[botwallet] = false;
}
function getBotWalletStatus(address botwallet) public view returns (bool) {
return botWallets[botwallet];
}
function allowtrading()external onlyOwner() {
canTrade = true;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
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 _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
// add the marketing wallet
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 marketingshare = newBalance.mul(80).div(100);
payable(marketingWallet).transfer(marketingshare);
newBalance -= marketingshare;
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!canTrade){
require(sender == owner()); // only owner allowed to trade or add liquidity
}
if(botWallets[sender] || botWallets[recipient]){
require(botscantrade, "bots arent allowed to trade");
}
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 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_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 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_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 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
} | _tokenTransfer | function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!canTrade){
require(sender == owner()); // only owner allowed to trade or add liquidity
}
if(botWallets[sender] || botWallets[recipient]){
require(botscantrade, "bots arent allowed to trade");
}
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
| //this method is responsible for taking all fee, if takeFee is true | LineComment | v0.8.9+commit.e5eed63a | Unlicense | ipfs://1f61365e99a29e2491db28fa8c1331548a9efdd3b4a7995173281253c7f748fe | {
"func_code_index": [
18170,
19289
]
} | 128 |
||
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | Ownable | function Ownable() public {
owner = msg.sender;
}
| /**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
261,
321
]
} | 129 |
|
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
644,
820
]
} | 130 |
|
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | ALT1Token | contract ALT1Token is Ownable, ERC20Basic {
using SafeMath for uint256;
string public constant name = "Altair VR presale token";
string public constant symbol = "ALT1";
uint8 public constant decimals = 18;
bool public mintingFinished = false;
mapping(address => uint256) public balances;
address[] public holders;
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
if (balances[_to] == 0) {
holders.push(_to);
}
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Current token is not transferred.
* After start official token sale ALT, you can exchange your ALT1 to ALT
*/
function transfer(address, uint256) public returns (bool) {
revert();
return false;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
modifier canMint() {
require(!mintingFinished);
_;
}
} | mint | function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
if (balances[_to] == 0) {
holders.push(_to);
}
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
| /**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
662,
1000
]
} | 131 |
|||
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | ALT1Token | contract ALT1Token is Ownable, ERC20Basic {
using SafeMath for uint256;
string public constant name = "Altair VR presale token";
string public constant symbol = "ALT1";
uint8 public constant decimals = 18;
bool public mintingFinished = false;
mapping(address => uint256) public balances;
address[] public holders;
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
if (balances[_to] == 0) {
holders.push(_to);
}
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Current token is not transferred.
* After start official token sale ALT, you can exchange your ALT1 to ALT
*/
function transfer(address, uint256) public returns (bool) {
revert();
return false;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
modifier canMint() {
require(!mintingFinished);
_;
}
} | finishMinting | function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
| /**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
1114,
1256
]
} | 132 |
|||
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | ALT1Token | contract ALT1Token is Ownable, ERC20Basic {
using SafeMath for uint256;
string public constant name = "Altair VR presale token";
string public constant symbol = "ALT1";
uint8 public constant decimals = 18;
bool public mintingFinished = false;
mapping(address => uint256) public balances;
address[] public holders;
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
if (balances[_to] == 0) {
holders.push(_to);
}
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Current token is not transferred.
* After start official token sale ALT, you can exchange your ALT1 to ALT
*/
function transfer(address, uint256) public returns (bool) {
revert();
return false;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
modifier canMint() {
require(!mintingFinished);
_;
}
} | transfer | function transfer(address, uint256) public returns (bool) {
revert();
return false;
}
| /**
* @dev Current token is not transferred.
* After start official token sale ALT, you can exchange your ALT1 to ALT
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
1392,
1493
]
} | 133 |
|||
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | ALT1Token | contract ALT1Token is Ownable, ERC20Basic {
using SafeMath for uint256;
string public constant name = "Altair VR presale token";
string public constant symbol = "ALT1";
uint8 public constant decimals = 18;
bool public mintingFinished = false;
mapping(address => uint256) public balances;
address[] public holders;
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
if (balances[_to] == 0) {
holders.push(_to);
}
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Current token is not transferred.
* After start official token sale ALT, you can exchange your ALT1 to ALT
*/
function transfer(address, uint256) public returns (bool) {
revert();
return false;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
modifier canMint() {
require(!mintingFinished);
_;
}
} | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
1699,
1811
]
} | 134 |
|||
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | Crowdsale | contract Crowdsale is Ownable {
using SafeMath for uint256;
uint256 public constant rate = 10000; // How many token units a buyer gets per wei
uint256 public constant cap = 80000000 ether; // Maximum amount of funds
bool public isFinalized = false;
uint256 public endTime = 1522540800; // End timestamps where investments are allowed
// 01-Apr-18 00:00:00 UTC
uint256 public bonusDecreaseDay = 1517529600; // First day with lower bonus 02-Feb-18 00:00:00 UTC
ALT1Token public token; // ALT1 token itself
ALT1Token public oldToken; // Old ALT1 token for balance converting
address public wallet; // Wallet of funds
uint256 public weiRaised; // Amount of raised money in wei
mapping(address => uint) public oldHolders;
uint256 public constant bonusByAmount = 70;
uint256 public constant amountForBonus = 50 ether;
mapping(uint => uint) public bonusesByDates;
uint[] public bonusesDates;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
function Crowdsale (ALT1Token _ALT1, ALT1Token _OldALT1, address _wallet) public {
assert(address(_ALT1) != address(0));
assert(address(_OldALT1) != address(0));
assert(_wallet != address(0));
assert(endTime > now);
assert(rate > 0);
assert(cap > 0);
token = _ALT1;
oldToken = _OldALT1;
bonusesDates = [
bonusDecreaseDay, // 02-Feb-18 00:00:00 UTC
1517788800, // 05-Feb-18 00:00:00 UTC
1518048000, // 08-Feb-18 00:00:00 UTC
1518307200, // 11-Feb-18 00:00:00 UTC
1518566400, // 14-Feb-18 00:00:00 UTC
1518825600, // 17-Feb-18 00:00:00 UTC
1519084800, // 20-Feb-18 00:00:00 UTC
1519344000, // 23-Feb-18 00:00:00 UTC
1519603200 // 26-Feb-18 00:00:00 UTC
];
bonusesByDates[bonusesDates[0]] = 70;
bonusesByDates[bonusesDates[1]] = 65;
bonusesByDates[bonusesDates[2]] = 60;
bonusesByDates[bonusesDates[3]] = 55;
bonusesByDates[bonusesDates[4]] = 50;
bonusesByDates[bonusesDates[5]] = 45;
bonusesByDates[bonusesDates[6]] = 40;
bonusesByDates[bonusesDates[7]] = 35;
bonusesByDates[bonusesDates[8]] = 30;
wallet = _wallet;
}
function () public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = tokensForWei(weiAmount);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function getBonus(uint256 _tokens) public view returns (uint256) {
if (_tokens.div(rate) >= amountForBonus && now <= bonusesDates[8]) return _tokens.mul(70).div(100);
if (now < bonusesDates[0]) return getBonusByDate(0, _tokens);
if (now < bonusesDates[1]) return getBonusByDate(1, _tokens);
if (now < bonusesDates[2]) return getBonusByDate(2, _tokens);
if (now < bonusesDates[3]) return getBonusByDate(3, _tokens);
if (now < bonusesDates[4]) return getBonusByDate(4, _tokens);
if (now < bonusesDates[5]) return getBonusByDate(5, _tokens);
if (now < bonusesDates[6]) return getBonusByDate(6, _tokens);
if (now < bonusesDates[7]) return getBonusByDate(7, _tokens);
if (now < bonusesDates[8]) return getBonusByDate(8, _tokens);
return _tokens.mul(25).div(100);
}
function getBonusByDate(uint256 _number, uint256 _tokens) public view returns (uint256 bonus) {
bonus = _tokens.mul(bonusesByDates[bonusesDates[_number]]).div(100);
}
function convertOldToken(address beneficiary) public oldTokenHolders(beneficiary) oldTokenFinalized {
uint amount = oldToken.balanceOf(beneficiary);
oldHolders[beneficiary] = amount;
weiRaised = weiRaised.add(amount.div(17000));
token.mint(beneficiary, amount);
}
function convertAllOldTokens(uint256 length, uint256 start) public oldTokenFinalized {
for (uint i = start; i < length; i++) {
if (oldHolders[oldToken.holders(i)] == 0) {
convertOldToken(oldToken.holders(i));
}
}
}
/**
* @dev Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
finalization();
Finalized();
isFinalized = true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool tokenMintingFinished = token.mintingFinished();
bool withinCap = token.totalSupply().add(tokensForWei(msg.value)) <= cap;
bool withinPeriod = now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool moreThanMinimumPayment = msg.value >= 0.05 ether;
return !tokenMintingFinished && withinCap && withinPeriod && nonZeroPurchase && moreThanMinimumPayment;
}
function tokensForWei(uint weiAmount) public view returns (uint tokens) {
tokens = weiAmount.mul(rate);
tokens = tokens.add(getBonus(tokens));
}
function finalization() internal {
token.finishMinting();
endTime = now;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
/**
* Throws if called by not an ALT0 holder or second time call for same ALT0 holder
*/
modifier oldTokenHolders(address beneficiary) {
require(oldToken.balanceOf(beneficiary) > 0);
require(oldHolders[beneficiary] == 0);
_;
}
modifier oldTokenFinalized() {
require(oldToken.mintingFinished());
_;
}
} | /**
* @title Crowdsale ALT1 presale token
*/ | NatSpecMultiLine | finalize | function finalize() onlyOwner public {
require(!isFinalized);
finalization();
Finalized();
isFinalized = true;
}
| /**
* @dev Calls the contract's finalization function.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
4700,
4842
]
} | 135 |
|
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | Crowdsale | contract Crowdsale is Ownable {
using SafeMath for uint256;
uint256 public constant rate = 10000; // How many token units a buyer gets per wei
uint256 public constant cap = 80000000 ether; // Maximum amount of funds
bool public isFinalized = false;
uint256 public endTime = 1522540800; // End timestamps where investments are allowed
// 01-Apr-18 00:00:00 UTC
uint256 public bonusDecreaseDay = 1517529600; // First day with lower bonus 02-Feb-18 00:00:00 UTC
ALT1Token public token; // ALT1 token itself
ALT1Token public oldToken; // Old ALT1 token for balance converting
address public wallet; // Wallet of funds
uint256 public weiRaised; // Amount of raised money in wei
mapping(address => uint) public oldHolders;
uint256 public constant bonusByAmount = 70;
uint256 public constant amountForBonus = 50 ether;
mapping(uint => uint) public bonusesByDates;
uint[] public bonusesDates;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
function Crowdsale (ALT1Token _ALT1, ALT1Token _OldALT1, address _wallet) public {
assert(address(_ALT1) != address(0));
assert(address(_OldALT1) != address(0));
assert(_wallet != address(0));
assert(endTime > now);
assert(rate > 0);
assert(cap > 0);
token = _ALT1;
oldToken = _OldALT1;
bonusesDates = [
bonusDecreaseDay, // 02-Feb-18 00:00:00 UTC
1517788800, // 05-Feb-18 00:00:00 UTC
1518048000, // 08-Feb-18 00:00:00 UTC
1518307200, // 11-Feb-18 00:00:00 UTC
1518566400, // 14-Feb-18 00:00:00 UTC
1518825600, // 17-Feb-18 00:00:00 UTC
1519084800, // 20-Feb-18 00:00:00 UTC
1519344000, // 23-Feb-18 00:00:00 UTC
1519603200 // 26-Feb-18 00:00:00 UTC
];
bonusesByDates[bonusesDates[0]] = 70;
bonusesByDates[bonusesDates[1]] = 65;
bonusesByDates[bonusesDates[2]] = 60;
bonusesByDates[bonusesDates[3]] = 55;
bonusesByDates[bonusesDates[4]] = 50;
bonusesByDates[bonusesDates[5]] = 45;
bonusesByDates[bonusesDates[6]] = 40;
bonusesByDates[bonusesDates[7]] = 35;
bonusesByDates[bonusesDates[8]] = 30;
wallet = _wallet;
}
function () public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = tokensForWei(weiAmount);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function getBonus(uint256 _tokens) public view returns (uint256) {
if (_tokens.div(rate) >= amountForBonus && now <= bonusesDates[8]) return _tokens.mul(70).div(100);
if (now < bonusesDates[0]) return getBonusByDate(0, _tokens);
if (now < bonusesDates[1]) return getBonusByDate(1, _tokens);
if (now < bonusesDates[2]) return getBonusByDate(2, _tokens);
if (now < bonusesDates[3]) return getBonusByDate(3, _tokens);
if (now < bonusesDates[4]) return getBonusByDate(4, _tokens);
if (now < bonusesDates[5]) return getBonusByDate(5, _tokens);
if (now < bonusesDates[6]) return getBonusByDate(6, _tokens);
if (now < bonusesDates[7]) return getBonusByDate(7, _tokens);
if (now < bonusesDates[8]) return getBonusByDate(8, _tokens);
return _tokens.mul(25).div(100);
}
function getBonusByDate(uint256 _number, uint256 _tokens) public view returns (uint256 bonus) {
bonus = _tokens.mul(bonusesByDates[bonusesDates[_number]]).div(100);
}
function convertOldToken(address beneficiary) public oldTokenHolders(beneficiary) oldTokenFinalized {
uint amount = oldToken.balanceOf(beneficiary);
oldHolders[beneficiary] = amount;
weiRaised = weiRaised.add(amount.div(17000));
token.mint(beneficiary, amount);
}
function convertAllOldTokens(uint256 length, uint256 start) public oldTokenFinalized {
for (uint i = start; i < length; i++) {
if (oldHolders[oldToken.holders(i)] == 0) {
convertOldToken(oldToken.holders(i));
}
}
}
/**
* @dev Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
finalization();
Finalized();
isFinalized = true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool tokenMintingFinished = token.mintingFinished();
bool withinCap = token.totalSupply().add(tokensForWei(msg.value)) <= cap;
bool withinPeriod = now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool moreThanMinimumPayment = msg.value >= 0.05 ether;
return !tokenMintingFinished && withinCap && withinPeriod && nonZeroPurchase && moreThanMinimumPayment;
}
function tokensForWei(uint weiAmount) public view returns (uint tokens) {
tokens = weiAmount.mul(rate);
tokens = tokens.add(getBonus(tokens));
}
function finalization() internal {
token.finishMinting();
endTime = now;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
/**
* Throws if called by not an ALT0 holder or second time call for same ALT0 holder
*/
modifier oldTokenHolders(address beneficiary) {
require(oldToken.balanceOf(beneficiary) > 0);
require(oldHolders[beneficiary] == 0);
_;
}
modifier oldTokenFinalized() {
require(oldToken.mintingFinished());
_;
}
} | /**
* @title Crowdsale ALT1 presale token
*/ | NatSpecMultiLine | forwardFunds | function forwardFunds() internal {
wallet.transfer(msg.value);
}
| // send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
4951,
5026
]
} | 136 |
|
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | Crowdsale | contract Crowdsale is Ownable {
using SafeMath for uint256;
uint256 public constant rate = 10000; // How many token units a buyer gets per wei
uint256 public constant cap = 80000000 ether; // Maximum amount of funds
bool public isFinalized = false;
uint256 public endTime = 1522540800; // End timestamps where investments are allowed
// 01-Apr-18 00:00:00 UTC
uint256 public bonusDecreaseDay = 1517529600; // First day with lower bonus 02-Feb-18 00:00:00 UTC
ALT1Token public token; // ALT1 token itself
ALT1Token public oldToken; // Old ALT1 token for balance converting
address public wallet; // Wallet of funds
uint256 public weiRaised; // Amount of raised money in wei
mapping(address => uint) public oldHolders;
uint256 public constant bonusByAmount = 70;
uint256 public constant amountForBonus = 50 ether;
mapping(uint => uint) public bonusesByDates;
uint[] public bonusesDates;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
function Crowdsale (ALT1Token _ALT1, ALT1Token _OldALT1, address _wallet) public {
assert(address(_ALT1) != address(0));
assert(address(_OldALT1) != address(0));
assert(_wallet != address(0));
assert(endTime > now);
assert(rate > 0);
assert(cap > 0);
token = _ALT1;
oldToken = _OldALT1;
bonusesDates = [
bonusDecreaseDay, // 02-Feb-18 00:00:00 UTC
1517788800, // 05-Feb-18 00:00:00 UTC
1518048000, // 08-Feb-18 00:00:00 UTC
1518307200, // 11-Feb-18 00:00:00 UTC
1518566400, // 14-Feb-18 00:00:00 UTC
1518825600, // 17-Feb-18 00:00:00 UTC
1519084800, // 20-Feb-18 00:00:00 UTC
1519344000, // 23-Feb-18 00:00:00 UTC
1519603200 // 26-Feb-18 00:00:00 UTC
];
bonusesByDates[bonusesDates[0]] = 70;
bonusesByDates[bonusesDates[1]] = 65;
bonusesByDates[bonusesDates[2]] = 60;
bonusesByDates[bonusesDates[3]] = 55;
bonusesByDates[bonusesDates[4]] = 50;
bonusesByDates[bonusesDates[5]] = 45;
bonusesByDates[bonusesDates[6]] = 40;
bonusesByDates[bonusesDates[7]] = 35;
bonusesByDates[bonusesDates[8]] = 30;
wallet = _wallet;
}
function () public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = tokensForWei(weiAmount);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function getBonus(uint256 _tokens) public view returns (uint256) {
if (_tokens.div(rate) >= amountForBonus && now <= bonusesDates[8]) return _tokens.mul(70).div(100);
if (now < bonusesDates[0]) return getBonusByDate(0, _tokens);
if (now < bonusesDates[1]) return getBonusByDate(1, _tokens);
if (now < bonusesDates[2]) return getBonusByDate(2, _tokens);
if (now < bonusesDates[3]) return getBonusByDate(3, _tokens);
if (now < bonusesDates[4]) return getBonusByDate(4, _tokens);
if (now < bonusesDates[5]) return getBonusByDate(5, _tokens);
if (now < bonusesDates[6]) return getBonusByDate(6, _tokens);
if (now < bonusesDates[7]) return getBonusByDate(7, _tokens);
if (now < bonusesDates[8]) return getBonusByDate(8, _tokens);
return _tokens.mul(25).div(100);
}
function getBonusByDate(uint256 _number, uint256 _tokens) public view returns (uint256 bonus) {
bonus = _tokens.mul(bonusesByDates[bonusesDates[_number]]).div(100);
}
function convertOldToken(address beneficiary) public oldTokenHolders(beneficiary) oldTokenFinalized {
uint amount = oldToken.balanceOf(beneficiary);
oldHolders[beneficiary] = amount;
weiRaised = weiRaised.add(amount.div(17000));
token.mint(beneficiary, amount);
}
function convertAllOldTokens(uint256 length, uint256 start) public oldTokenFinalized {
for (uint i = start; i < length; i++) {
if (oldHolders[oldToken.holders(i)] == 0) {
convertOldToken(oldToken.holders(i));
}
}
}
/**
* @dev Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
finalization();
Finalized();
isFinalized = true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool tokenMintingFinished = token.mintingFinished();
bool withinCap = token.totalSupply().add(tokensForWei(msg.value)) <= cap;
bool withinPeriod = now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool moreThanMinimumPayment = msg.value >= 0.05 ether;
return !tokenMintingFinished && withinCap && withinPeriod && nonZeroPurchase && moreThanMinimumPayment;
}
function tokensForWei(uint weiAmount) public view returns (uint tokens) {
tokens = weiAmount.mul(rate);
tokens = tokens.add(getBonus(tokens));
}
function finalization() internal {
token.finishMinting();
endTime = now;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
/**
* Throws if called by not an ALT0 holder or second time call for same ALT0 holder
*/
modifier oldTokenHolders(address beneficiary) {
require(oldToken.balanceOf(beneficiary) > 0);
require(oldHolders[beneficiary] == 0);
_;
}
modifier oldTokenFinalized() {
require(oldToken.mintingFinished());
_;
}
} | /**
* @title Crowdsale ALT1 presale token
*/ | NatSpecMultiLine | validPurchase | function validPurchase() internal view returns (bool) {
bool tokenMintingFinished = token.mintingFinished();
bool withinCap = token.totalSupply().add(tokensForWei(msg.value)) <= cap;
bool withinPeriod = now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool moreThanMinimumPayment = msg.value >= 0.05 ether;
return !tokenMintingFinished && withinCap && withinPeriod && nonZeroPurchase && moreThanMinimumPayment;
}
| // @return true if the transaction can buy tokens | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
5082,
5538
]
} | 137 |
|
Crowdsale | Crowdsale.sol | 0x2029f1376726e9b1e59a9eb0c40656f1949e6684 | Solidity | Crowdsale | contract Crowdsale is Ownable {
using SafeMath for uint256;
uint256 public constant rate = 10000; // How many token units a buyer gets per wei
uint256 public constant cap = 80000000 ether; // Maximum amount of funds
bool public isFinalized = false;
uint256 public endTime = 1522540800; // End timestamps where investments are allowed
// 01-Apr-18 00:00:00 UTC
uint256 public bonusDecreaseDay = 1517529600; // First day with lower bonus 02-Feb-18 00:00:00 UTC
ALT1Token public token; // ALT1 token itself
ALT1Token public oldToken; // Old ALT1 token for balance converting
address public wallet; // Wallet of funds
uint256 public weiRaised; // Amount of raised money in wei
mapping(address => uint) public oldHolders;
uint256 public constant bonusByAmount = 70;
uint256 public constant amountForBonus = 50 ether;
mapping(uint => uint) public bonusesByDates;
uint[] public bonusesDates;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
function Crowdsale (ALT1Token _ALT1, ALT1Token _OldALT1, address _wallet) public {
assert(address(_ALT1) != address(0));
assert(address(_OldALT1) != address(0));
assert(_wallet != address(0));
assert(endTime > now);
assert(rate > 0);
assert(cap > 0);
token = _ALT1;
oldToken = _OldALT1;
bonusesDates = [
bonusDecreaseDay, // 02-Feb-18 00:00:00 UTC
1517788800, // 05-Feb-18 00:00:00 UTC
1518048000, // 08-Feb-18 00:00:00 UTC
1518307200, // 11-Feb-18 00:00:00 UTC
1518566400, // 14-Feb-18 00:00:00 UTC
1518825600, // 17-Feb-18 00:00:00 UTC
1519084800, // 20-Feb-18 00:00:00 UTC
1519344000, // 23-Feb-18 00:00:00 UTC
1519603200 // 26-Feb-18 00:00:00 UTC
];
bonusesByDates[bonusesDates[0]] = 70;
bonusesByDates[bonusesDates[1]] = 65;
bonusesByDates[bonusesDates[2]] = 60;
bonusesByDates[bonusesDates[3]] = 55;
bonusesByDates[bonusesDates[4]] = 50;
bonusesByDates[bonusesDates[5]] = 45;
bonusesByDates[bonusesDates[6]] = 40;
bonusesByDates[bonusesDates[7]] = 35;
bonusesByDates[bonusesDates[8]] = 30;
wallet = _wallet;
}
function () public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = tokensForWei(weiAmount);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function getBonus(uint256 _tokens) public view returns (uint256) {
if (_tokens.div(rate) >= amountForBonus && now <= bonusesDates[8]) return _tokens.mul(70).div(100);
if (now < bonusesDates[0]) return getBonusByDate(0, _tokens);
if (now < bonusesDates[1]) return getBonusByDate(1, _tokens);
if (now < bonusesDates[2]) return getBonusByDate(2, _tokens);
if (now < bonusesDates[3]) return getBonusByDate(3, _tokens);
if (now < bonusesDates[4]) return getBonusByDate(4, _tokens);
if (now < bonusesDates[5]) return getBonusByDate(5, _tokens);
if (now < bonusesDates[6]) return getBonusByDate(6, _tokens);
if (now < bonusesDates[7]) return getBonusByDate(7, _tokens);
if (now < bonusesDates[8]) return getBonusByDate(8, _tokens);
return _tokens.mul(25).div(100);
}
function getBonusByDate(uint256 _number, uint256 _tokens) public view returns (uint256 bonus) {
bonus = _tokens.mul(bonusesByDates[bonusesDates[_number]]).div(100);
}
function convertOldToken(address beneficiary) public oldTokenHolders(beneficiary) oldTokenFinalized {
uint amount = oldToken.balanceOf(beneficiary);
oldHolders[beneficiary] = amount;
weiRaised = weiRaised.add(amount.div(17000));
token.mint(beneficiary, amount);
}
function convertAllOldTokens(uint256 length, uint256 start) public oldTokenFinalized {
for (uint i = start; i < length; i++) {
if (oldHolders[oldToken.holders(i)] == 0) {
convertOldToken(oldToken.holders(i));
}
}
}
/**
* @dev Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
finalization();
Finalized();
isFinalized = true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool tokenMintingFinished = token.mintingFinished();
bool withinCap = token.totalSupply().add(tokensForWei(msg.value)) <= cap;
bool withinPeriod = now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool moreThanMinimumPayment = msg.value >= 0.05 ether;
return !tokenMintingFinished && withinCap && withinPeriod && nonZeroPurchase && moreThanMinimumPayment;
}
function tokensForWei(uint weiAmount) public view returns (uint tokens) {
tokens = weiAmount.mul(rate);
tokens = tokens.add(getBonus(tokens));
}
function finalization() internal {
token.finishMinting();
endTime = now;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
/**
* Throws if called by not an ALT0 holder or second time call for same ALT0 holder
*/
modifier oldTokenHolders(address beneficiary) {
require(oldToken.balanceOf(beneficiary) > 0);
require(oldHolders[beneficiary] == 0);
_;
}
modifier oldTokenFinalized() {
require(oldToken.mintingFinished());
_;
}
} | /**
* @title Crowdsale ALT1 presale token
*/ | NatSpecMultiLine | hasEnded | function hasEnded() public view returns (bool) {
return now > endTime;
}
| // @return true if crowdsale event has ended | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://c25574a60ff107cffcf4c6de0de1463e5bf7a8bb64be3760966277d3098f4177 | {
"func_code_index": [
5845,
5928
]
} | 138 |
|
CulturalChain | CulturalChain.sol | 0x3d8c5681a4f4faf49e5dc9a24f2c7372d7cca65b | Solidity | CulturalChain | contract CulturalChain is EIP20Interface {
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
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; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
function CulturalChain(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | CulturalChain | function CulturalChain(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
| //An identifier: eg SBX | LineComment | v0.4.21+commit.dfe3193c | bzzr://5f212b015c93277165f273868130d56d7b0e0d68c9b703d4583d46665f97a3a8 | {
"func_code_index": [
730,
1392
]
} | 139 |
|||
Escrow | Escrow.sol | 0x8df8d68c2cc0604b45ce5b69d6556722736a18bb | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://c62b407954252e407fbac0052997bfe78e453869286a47a4ea337e31c2196fac | {
"func_code_index": [
95,
524
]
} | 140 |
|
Escrow | Escrow.sol | 0x8df8d68c2cc0604b45ce5b69d6556722736a18bb | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
| /**
* @dev Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://c62b407954252e407fbac0052997bfe78e453869286a47a4ea337e31c2196fac | {
"func_code_index": [
614,
914
]
} | 141 |
|
Escrow | Escrow.sol | 0x8df8d68c2cc0604b45ce5b69d6556722736a18bb | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://c62b407954252e407fbac0052997bfe78e453869286a47a4ea337e31c2196fac | {
"func_code_index": [
1034,
1162
]
} | 142 |
|
Escrow | Escrow.sol | 0x8df8d68c2cc0604b45ce5b69d6556722736a18bb | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://c62b407954252e407fbac0052997bfe78e453869286a47a4ea337e31c2196fac | {
"func_code_index": [
1232,
1378
]
} | 143 |
|
Escrow | Escrow.sol | 0x8df8d68c2cc0604b45ce5b69d6556722736a18bb | Solidity | Escrow | contract Escrow is Ownable {
using SafeMath for uint256;
struct Stage {
uint releaseTime;
uint percent;
bool transferred;
}
mapping (uint => Stage) public stages;
uint public stageCount;
uint public stopDay;
uint public startBalance = 0;
constructor(uint _stopDay) public {
stopDay = _stopDay;
}
function() payable public {
}
//1% - 100, 10% - 1000 50% - 5000
function addStage(uint _releaseTime, uint _percent) onlyOwner public {
require(_percent >= 100);
require(_releaseTime > stages[stageCount].releaseTime);
stageCount++;
stages[stageCount].releaseTime = _releaseTime;
stages[stageCount].percent = _percent;
}
function getETH(uint _stage, address _to) onlyManager external {
require(stages[_stage].releaseTime < now);
require(!stages[_stage].transferred);
require(_to != address(0));
if (startBalance == 0) {
startBalance = address(this).balance;
}
uint val = valueFromPercent(startBalance, stages[_stage].percent);
stages[_stage].transferred = true;
_to.transfer(val);
}
function getAllETH(address _to) onlyManager external {
require(stopDay < now);
require(address(this).balance > 0);
require(_to != address(0));
_to.transfer(address(this).balance);
}
function transferETH(address _to) onlyOwner external {
require(address(this).balance > 0);
require(_to != address(0));
_to.transfer(address(this).balance);
}
//1% - 100, 10% - 1000 50% - 5000
function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) {
uint _amount = _value.mul(_percent).div(10000);
return (_amount);
}
function setStopDay(uint _stopDay) onlyOwner external {
stopDay = _stopDay;
}
} | /**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/ | NatSpecMultiLine | addStage | function addStage(uint _releaseTime, uint _percent) onlyOwner public {
require(_percent >= 100);
require(_releaseTime > stages[stageCount].releaseTime);
stageCount++;
stages[stageCount].releaseTime = _releaseTime;
stages[stageCount].percent = _percent;
}
| //1% - 100, 10% - 1000 50% - 5000 | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://c62b407954252e407fbac0052997bfe78e453869286a47a4ea337e31c2196fac | {
"func_code_index": [
473,
782
]
} | 144 |
|
Escrow | Escrow.sol | 0x8df8d68c2cc0604b45ce5b69d6556722736a18bb | Solidity | Escrow | contract Escrow is Ownable {
using SafeMath for uint256;
struct Stage {
uint releaseTime;
uint percent;
bool transferred;
}
mapping (uint => Stage) public stages;
uint public stageCount;
uint public stopDay;
uint public startBalance = 0;
constructor(uint _stopDay) public {
stopDay = _stopDay;
}
function() payable public {
}
//1% - 100, 10% - 1000 50% - 5000
function addStage(uint _releaseTime, uint _percent) onlyOwner public {
require(_percent >= 100);
require(_releaseTime > stages[stageCount].releaseTime);
stageCount++;
stages[stageCount].releaseTime = _releaseTime;
stages[stageCount].percent = _percent;
}
function getETH(uint _stage, address _to) onlyManager external {
require(stages[_stage].releaseTime < now);
require(!stages[_stage].transferred);
require(_to != address(0));
if (startBalance == 0) {
startBalance = address(this).balance;
}
uint val = valueFromPercent(startBalance, stages[_stage].percent);
stages[_stage].transferred = true;
_to.transfer(val);
}
function getAllETH(address _to) onlyManager external {
require(stopDay < now);
require(address(this).balance > 0);
require(_to != address(0));
_to.transfer(address(this).balance);
}
function transferETH(address _to) onlyOwner external {
require(address(this).balance > 0);
require(_to != address(0));
_to.transfer(address(this).balance);
}
//1% - 100, 10% - 1000 50% - 5000
function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) {
uint _amount = _value.mul(_percent).div(10000);
return (_amount);
}
function setStopDay(uint _stopDay) onlyOwner external {
stopDay = _stopDay;
}
} | /**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/ | NatSpecMultiLine | valueFromPercent | function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) {
uint _amount = _value.mul(_percent).div(10000);
return (_amount);
}
| //1% - 100, 10% - 1000 50% - 5000 | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://c62b407954252e407fbac0052997bfe78e453869286a47a4ea337e31c2196fac | {
"func_code_index": [
1724,
1914
]
} | 145 |
|
EqualToken | EqualToken.sol | 0x5824f275dab2c59b8972a1fda45ff404c9a703e3 | 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);
event Burn(address indexed from, uint256 value);
} | totalSupply | function totalSupply() constant returns (uint256 supply);
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://03157a881cbeb271c2ac473f7a83ac498e77628ebad3e7cf4d521bd02770c22e | {
"func_code_index": [
60,
122
]
} | 146 |
|||
EqualToken | EqualToken.sol | 0x5824f275dab2c59b8972a1fda45ff404c9a703e3 | 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);
event Burn(address indexed from, 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.18+commit.9cf6e910 | bzzr://03157a881cbeb271c2ac473f7a83ac498e77628ebad3e7cf4d521bd02770c22e | {
"func_code_index": [
230,
305
]
} | 147 |
|||
EqualToken | EqualToken.sol | 0x5824f275dab2c59b8972a1fda45ff404c9a703e3 | 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);
event Burn(address indexed from, 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.18+commit.9cf6e910 | bzzr://03157a881cbeb271c2ac473f7a83ac498e77628ebad3e7cf4d521bd02770c22e | {
"func_code_index": [
540,
615
]
} | 148 |
|||
EqualToken | EqualToken.sol | 0x5824f275dab2c59b8972a1fda45ff404c9a703e3 | 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);
event Burn(address indexed from, 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.18+commit.9cf6e910 | bzzr://03157a881cbeb271c2ac473f7a83ac498e77628ebad3e7cf4d521bd02770c22e | {
"func_code_index": [
938,
1032
]
} | 149 |
|||
EqualToken | EqualToken.sol | 0x5824f275dab2c59b8972a1fda45ff404c9a703e3 | 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);
event Burn(address indexed from, 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.18+commit.9cf6e910 | bzzr://03157a881cbeb271c2ac473f7a83ac498e77628ebad3e7cf4d521bd02770c22e | {
"func_code_index": [
1320,
1399
]
} | 150 |
|||
EqualToken | EqualToken.sol | 0x5824f275dab2c59b8972a1fda45ff404c9a703e3 | 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);
event Burn(address indexed from, 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.18+commit.9cf6e910 | bzzr://03157a881cbeb271c2ac473f7a83ac498e77628ebad3e7cf4d521bd02770c22e | {
"func_code_index": [
1607,
1702
]
} | 151 |
|||
EqualToken | EqualToken.sol | 0x5824f275dab2c59b8972a1fda45ff404c9a703e3 | Solidity | EqualToken | contract EqualToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
revert();
}
/* 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; //fancy name: eg Simon Bucks
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
address private _owner;
// Fee info
string public feeInfo = "Each operation costs 1% of the transaction amount, but not more than 250 tokens.";
function EqualToken() {
_totalSupply = 800000000000000000000000000;
_owner=msg.sender;
balances[msg.sender] =_totalSupply;
// Airdrop Allocation
allocate(0xeeEb0f191c4E2ee96E1399937a5241fA1E9f9A6e,20); // Airdrop Round One
allocate(0x3CF9d0484790a1a24cfb1A51f8BEf39b6F1322d6,20); // Airdrop Round Two
allocate(0x64d1832cf8879A903af86E60fF9ed549648B2Bda,5); // Airdrop Round Three
// Adoption Allocation
allocate(0x0b6cFbc459efF6B12238380AC2A26926896eaFA2,35); // Seed Offerings
// Internal Allocation
allocate(0xaBf029361BeCB2bE58011AD874C6eAbCD4c84D09,20); // Team
maxFee=250; // max fee for transfer
name = "EQUAL Token"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposes
symbol = "EQL"; // Set the symbol for display purposes
}
function allocate(address _address,uint256 percent) private{
uint256 bal=_totalSupply.onePercent().mul(percent);
//balances[_address]=bal;
withoutFee[_address]=true;
doTransfer(msg.sender,_address,bal,0);
}
function setWithoutFee(address _address,bool _withoutFee) public {
require(_owner==msg.sender);
withoutFee[_address]=_withoutFee;
}
/* 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)) { revert(); }
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)) { revert(); }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.18+commit.9cf6e910 | bzzr://03157a881cbeb271c2ac473f7a83ac498e77628ebad3e7cf4d521bd02770c22e | {
"func_code_index": [
2384,
3192
]
} | 152 |
|||
Crowdsale | Crowdsale.sol | 0xedb2675b05d3c89cd2800b8f23567bb77a990fe4 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
// uint256 durationInMinutes;
// address where funds are collected
address public wallet;
// token address
address public addressOfTokenUsedAsReward;
uint256 public price = 300;
uint256 public minBuy;
uint256 public maxBuy;
token tokenReward;
// mapping (address => uint) public contributions;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
// uint256 public endTime;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() {
//You will change this to your wallet where you need the ETH
wallet = 0xc076b054EF62aCCE747175F698FC3Dbec9B7A36F;
// durationInMinutes = _durationInMinutes;
//Here will come the checksum address we got
addressOfTokenUsedAsReward = 0xd62e9252F1615F5c1133F060CF091aCb4b0faa2b;
tokenReward = token(addressOfTokenUsedAsReward);
}
bool public started = false;
function startSale(uint256 _delayInMinutes){
if (msg.sender != wallet) throw;
startTime = now + _delayInMinutes*1 minutes;
started = true;
}
function stopSale(){
if(msg.sender != wallet) throw;
started = false;
}
function setPrice(uint256 _price){
if(msg.sender != wallet) throw;
price = _price;
}
function setMinBuy(uint256 _minBuy){
if(msg.sender!=wallet) throw;
minBuy = _minBuy;
}
function setMaxBuy(uint256 _maxBuy){
if(msg.sender != wallet) throw;
maxBuy = _maxBuy;
}
function changeWallet(address _wallet){
if(msg.sender != wallet) throw;
wallet = _wallet;
}
function changeTokenReward(address _token){
if(msg.sender!=wallet) throw;
tokenReward = token(_token);
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be sent
uint256 tokens = (weiAmount) * price;//weiamount * price
if(minBuy!=0){
if(tokens < minBuy*10**18) throw;
}
if(maxBuy!=0){
if(tokens > maxBuy*10**18) throw;
}
// update state
weiRaised = weiRaised.add(weiAmount);
// if(contributions[msg.sender].add(weiAmount)>10*10**18) throw;
// contributions[msg.sender] = contributions[msg.sender].add(weiAmount);
tokenReward.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
// wallet.transfer(msg.value);
if (!wallet.send(msg.value)) {
throw;
}
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = started&&(now>=startTime);
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function withdrawTokens(uint256 _amount) {
if(msg.sender!=wallet) throw;
tokenReward.transfer(wallet,_amount);
}
} | function () payable {
buyTokens(msg.sender);
}
| // fallback function can be used to buy tokens | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://39bf429bbea86824880515a5e65f781c2fae30581bdaf87b476b674f8148c2fd | {
"func_code_index": [
2223,
2280
]
} | 153 |
||||
Crowdsale | Crowdsale.sol | 0xedb2675b05d3c89cd2800b8f23567bb77a990fe4 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
// uint256 durationInMinutes;
// address where funds are collected
address public wallet;
// token address
address public addressOfTokenUsedAsReward;
uint256 public price = 300;
uint256 public minBuy;
uint256 public maxBuy;
token tokenReward;
// mapping (address => uint) public contributions;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
// uint256 public endTime;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() {
//You will change this to your wallet where you need the ETH
wallet = 0xc076b054EF62aCCE747175F698FC3Dbec9B7A36F;
// durationInMinutes = _durationInMinutes;
//Here will come the checksum address we got
addressOfTokenUsedAsReward = 0xd62e9252F1615F5c1133F060CF091aCb4b0faa2b;
tokenReward = token(addressOfTokenUsedAsReward);
}
bool public started = false;
function startSale(uint256 _delayInMinutes){
if (msg.sender != wallet) throw;
startTime = now + _delayInMinutes*1 minutes;
started = true;
}
function stopSale(){
if(msg.sender != wallet) throw;
started = false;
}
function setPrice(uint256 _price){
if(msg.sender != wallet) throw;
price = _price;
}
function setMinBuy(uint256 _minBuy){
if(msg.sender!=wallet) throw;
minBuy = _minBuy;
}
function setMaxBuy(uint256 _maxBuy){
if(msg.sender != wallet) throw;
maxBuy = _maxBuy;
}
function changeWallet(address _wallet){
if(msg.sender != wallet) throw;
wallet = _wallet;
}
function changeTokenReward(address _token){
if(msg.sender!=wallet) throw;
tokenReward = token(_token);
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be sent
uint256 tokens = (weiAmount) * price;//weiamount * price
if(minBuy!=0){
if(tokens < minBuy*10**18) throw;
}
if(maxBuy!=0){
if(tokens > maxBuy*10**18) throw;
}
// update state
weiRaised = weiRaised.add(weiAmount);
// if(contributions[msg.sender].add(weiAmount)>10*10**18) throw;
// contributions[msg.sender] = contributions[msg.sender].add(weiAmount);
tokenReward.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
// wallet.transfer(msg.value);
if (!wallet.send(msg.value)) {
throw;
}
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = started&&(now>=startTime);
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function withdrawTokens(uint256 _amount) {
if(msg.sender!=wallet) throw;
tokenReward.transfer(wallet,_amount);
}
} | buyTokens | function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be sent
uint256 tokens = (weiAmount) * price;//weiamount * price
if(minBuy!=0){
if(tokens < minBuy*10**18) throw;
}
if(maxBuy!=0){
if(tokens > maxBuy*10**18) throw;
}
// update state
weiRaised = weiRaised.add(weiAmount);
// if(contributions[msg.sender].add(weiAmount)>10*10**18) throw;
// contributions[msg.sender] = contributions[msg.sender].add(weiAmount);
tokenReward.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
| // low level token purchase function | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://39bf429bbea86824880515a5e65f781c2fae30581bdaf87b476b674f8148c2fd | {
"func_code_index": [
2323,
3085
]
} | 154 |
|||
Crowdsale | Crowdsale.sol | 0xedb2675b05d3c89cd2800b8f23567bb77a990fe4 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
// uint256 durationInMinutes;
// address where funds are collected
address public wallet;
// token address
address public addressOfTokenUsedAsReward;
uint256 public price = 300;
uint256 public minBuy;
uint256 public maxBuy;
token tokenReward;
// mapping (address => uint) public contributions;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
// uint256 public endTime;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() {
//You will change this to your wallet where you need the ETH
wallet = 0xc076b054EF62aCCE747175F698FC3Dbec9B7A36F;
// durationInMinutes = _durationInMinutes;
//Here will come the checksum address we got
addressOfTokenUsedAsReward = 0xd62e9252F1615F5c1133F060CF091aCb4b0faa2b;
tokenReward = token(addressOfTokenUsedAsReward);
}
bool public started = false;
function startSale(uint256 _delayInMinutes){
if (msg.sender != wallet) throw;
startTime = now + _delayInMinutes*1 minutes;
started = true;
}
function stopSale(){
if(msg.sender != wallet) throw;
started = false;
}
function setPrice(uint256 _price){
if(msg.sender != wallet) throw;
price = _price;
}
function setMinBuy(uint256 _minBuy){
if(msg.sender!=wallet) throw;
minBuy = _minBuy;
}
function setMaxBuy(uint256 _maxBuy){
if(msg.sender != wallet) throw;
maxBuy = _maxBuy;
}
function changeWallet(address _wallet){
if(msg.sender != wallet) throw;
wallet = _wallet;
}
function changeTokenReward(address _token){
if(msg.sender!=wallet) throw;
tokenReward = token(_token);
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be sent
uint256 tokens = (weiAmount) * price;//weiamount * price
if(minBuy!=0){
if(tokens < minBuy*10**18) throw;
}
if(maxBuy!=0){
if(tokens > maxBuy*10**18) throw;
}
// update state
weiRaised = weiRaised.add(weiAmount);
// if(contributions[msg.sender].add(weiAmount)>10*10**18) throw;
// contributions[msg.sender] = contributions[msg.sender].add(weiAmount);
tokenReward.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
// wallet.transfer(msg.value);
if (!wallet.send(msg.value)) {
throw;
}
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = started&&(now>=startTime);
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function withdrawTokens(uint256 _amount) {
if(msg.sender!=wallet) throw;
tokenReward.transfer(wallet,_amount);
}
} | forwardFunds | function forwardFunds() internal {
// wallet.transfer(msg.value);
if (!wallet.send(msg.value)) {
throw;
}
}
| // send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://39bf429bbea86824880515a5e65f781c2fae30581bdaf87b476b674f8148c2fd | {
"func_code_index": [
3194,
3329
]
} | 155 |
|||
Crowdsale | Crowdsale.sol | 0xedb2675b05d3c89cd2800b8f23567bb77a990fe4 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
// uint256 durationInMinutes;
// address where funds are collected
address public wallet;
// token address
address public addressOfTokenUsedAsReward;
uint256 public price = 300;
uint256 public minBuy;
uint256 public maxBuy;
token tokenReward;
// mapping (address => uint) public contributions;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
// uint256 public endTime;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() {
//You will change this to your wallet where you need the ETH
wallet = 0xc076b054EF62aCCE747175F698FC3Dbec9B7A36F;
// durationInMinutes = _durationInMinutes;
//Here will come the checksum address we got
addressOfTokenUsedAsReward = 0xd62e9252F1615F5c1133F060CF091aCb4b0faa2b;
tokenReward = token(addressOfTokenUsedAsReward);
}
bool public started = false;
function startSale(uint256 _delayInMinutes){
if (msg.sender != wallet) throw;
startTime = now + _delayInMinutes*1 minutes;
started = true;
}
function stopSale(){
if(msg.sender != wallet) throw;
started = false;
}
function setPrice(uint256 _price){
if(msg.sender != wallet) throw;
price = _price;
}
function setMinBuy(uint256 _minBuy){
if(msg.sender!=wallet) throw;
minBuy = _minBuy;
}
function setMaxBuy(uint256 _maxBuy){
if(msg.sender != wallet) throw;
maxBuy = _maxBuy;
}
function changeWallet(address _wallet){
if(msg.sender != wallet) throw;
wallet = _wallet;
}
function changeTokenReward(address _token){
if(msg.sender!=wallet) throw;
tokenReward = token(_token);
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be sent
uint256 tokens = (weiAmount) * price;//weiamount * price
if(minBuy!=0){
if(tokens < minBuy*10**18) throw;
}
if(maxBuy!=0){
if(tokens > maxBuy*10**18) throw;
}
// update state
weiRaised = weiRaised.add(weiAmount);
// if(contributions[msg.sender].add(weiAmount)>10*10**18) throw;
// contributions[msg.sender] = contributions[msg.sender].add(weiAmount);
tokenReward.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
// wallet.transfer(msg.value);
if (!wallet.send(msg.value)) {
throw;
}
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = started&&(now>=startTime);
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function withdrawTokens(uint256 _amount) {
if(msg.sender!=wallet) throw;
tokenReward.transfer(wallet,_amount);
}
} | validPurchase | function validPurchase() internal constant returns (bool) {
bool withinPeriod = started&&(now>=startTime);
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
| // @return true if the transaction can buy tokens | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://39bf429bbea86824880515a5e65f781c2fae30581bdaf87b476b674f8148c2fd | {
"func_code_index": [
3385,
3593
]
} | 156 |
|||
CFolioFarm | contracts/src/investment/CFolioFarm.sol | 0xb18104e050f1e8e828dd2b0260f7feb1c2178752 | Solidity | CFolioFarm | contract CFolioFarm is IFarm, ICFolioFarm, Ownable, ERC20Recovery {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
uint256 public override periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 14 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 private availableRewards;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
// Unique name of this farm instance, used in controller
string private _farmName;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
// The address of the controller
IController public override controller;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
event RewardAdded(uint256 reward);
event AssetAdded(address indexed user, uint256 amount, uint256 totalAmount);
event AssetRemoved(address indexed user, uint256 amount, uint256 totalAmount);
event ShareAdded(address indexed user, uint256 amount);
event ShareRemoved(address indexed user, uint256 amount);
event RewardPaid(
address indexed account,
address indexed user,
uint256 reward
);
event RewardsDurationUpdated(uint256 newDuration);
event ControllerChanged(address newController);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyController {
require(_msgSender() == address(controller), 'not controller');
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
constructor(
address _owner,
string memory _name,
address _controller
) {
// Validate parameters
require(_owner != address(0), 'Invalid owner');
require(_controller != address(0), 'Invalid controller');
// Initialize {Ownable}
transferOwnership(_owner);
// Initialize state
_farmName = _name;
controller = IController(_controller);
}
//////////////////////////////////////////////////////////////////////////////
// Views
//////////////////////////////////////////////////////////////////////////////
function farmName() external view override returns (string memory) {
return _farmName;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return
_balances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
function getUIData(address account)
external
view
override
returns (uint256[5] memory)
{
uint256[5] memory result =
[
_totalSupply,
_balances[account],
rewardsDuration,
rewardRate.mul(rewardsDuration),
earned(account)
];
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Mutators
//////////////////////////////////////////////////////////////////////////////
function addAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_balances[account] = _balances[account].add(amount);
// Dispatch event
emit AssetAdded(account, amount, _balances[account]);
}
function removeAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_balances[account] = _balances[account].sub(amount);
// Dispatch event
emit AssetRemoved(account, amount, _balances[account]);
}
function addShares(address account, uint256 amount)
external
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
// Notify controller
controller.onDeposit(amount);
// Dispatch event
emit ShareAdded(account, amount);
}
function removeShares(address account, uint256 amount)
public
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
// Notify controller
controller.onWithdraw(amount);
// Dispatch event
emit ShareRemoved(account, amount);
}
function getReward(address account, address rewardRecipient)
public
override
onlyOwner
updateReward(account)
{
// Load state
uint256 reward = rewards[account];
if (reward > 0) {
// Update state
rewards[account] = 0;
availableRewards = availableRewards.sub(reward);
// Notify controller
controller.payOutRewards(rewardRecipient, reward);
// Dispatch event
emit RewardPaid(account, rewardRecipient, reward);
}
}
function exit(address account, address rewardRecipient)
external
override
onlyOwner
{
removeShares(account, _balances[account]);
getReward(account, rewardRecipient);
}
//////////////////////////////////////////////////////////////////////////////
// Restricted functions
//////////////////////////////////////////////////////////////////////////////
function setController(address newController)
external
override
onlyController
{
// Update state
controller = IController(newController);
// Dispatch event
emit ControllerChanged(newController);
}
function notifyRewardAmount(uint256 reward)
external
override
onlyController
updateReward(address(0))
{
// Update state
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
// solhint-disable-next-line not-rely-on-time
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
availableRewards = availableRewards.add(reward);
// Validate state
//
// Ensure the provided reward amount is not more than the balance in the
// contract.
//
// This keeps the reward rate in the right range, preventing overflows due
// to very high values of rewardRate in the earned and rewardsPerToken
// functions.
//
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
//
require(
rewardRate <= availableRewards.div(rewardsDuration),
'Provided reward too high'
);
// Update state
// solhint-disable-next-line not-rely-on-time
lastUpdateTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
periodFinish = block.timestamp.add(rewardsDuration);
// Dispatch event
emit RewardAdded(reward);
}
/**
* @dev We don't have any rebalancing here
*/
// solhint-disable-next-line no-empty-blocks
function rebalance() external override onlyController {}
/**
* @dev Added to support recovering LP Rewards from other systems to be
* distributed to holders
*/
function recoverERC20(
address recipient,
address tokenAddress,
uint256 tokenAmount
) external onlyController {
// Call ancestor
_recoverERC20(recipient, tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration)
external
override
onlyController
{
// Validate state
require(
// solhint-disable-next-line not-rely-on-time
periodFinish == 0 || block.timestamp > periodFinish,
'Reward period not finished'
);
// Update state
rewardsDuration = _rewardsDuration;
// Dispatch event
emit RewardsDurationUpdated(rewardsDuration);
}
} | /**
* @notice Farm is owned by a CFolio contract.
*
* All state modifing calls are only allowed from this owner.
*/ | NatSpecMultiLine | farmName | function farmName() external view override returns (string memory) {
return _farmName;
}
| ////////////////////////////////////////////////////////////////////////////// | NatSpecSingleLine | v0.7.4+commit.3f05b770 | Apache-2.0 | {
"func_code_index": [
2914,
3010
]
} | 157 |
|
CFolioFarm | contracts/src/investment/CFolioFarm.sol | 0xb18104e050f1e8e828dd2b0260f7feb1c2178752 | Solidity | CFolioFarm | contract CFolioFarm is IFarm, ICFolioFarm, Ownable, ERC20Recovery {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
uint256 public override periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 14 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 private availableRewards;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
// Unique name of this farm instance, used in controller
string private _farmName;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
// The address of the controller
IController public override controller;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
event RewardAdded(uint256 reward);
event AssetAdded(address indexed user, uint256 amount, uint256 totalAmount);
event AssetRemoved(address indexed user, uint256 amount, uint256 totalAmount);
event ShareAdded(address indexed user, uint256 amount);
event ShareRemoved(address indexed user, uint256 amount);
event RewardPaid(
address indexed account,
address indexed user,
uint256 reward
);
event RewardsDurationUpdated(uint256 newDuration);
event ControllerChanged(address newController);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyController {
require(_msgSender() == address(controller), 'not controller');
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
constructor(
address _owner,
string memory _name,
address _controller
) {
// Validate parameters
require(_owner != address(0), 'Invalid owner');
require(_controller != address(0), 'Invalid controller');
// Initialize {Ownable}
transferOwnership(_owner);
// Initialize state
_farmName = _name;
controller = IController(_controller);
}
//////////////////////////////////////////////////////////////////////////////
// Views
//////////////////////////////////////////////////////////////////////////////
function farmName() external view override returns (string memory) {
return _farmName;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return
_balances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
function getUIData(address account)
external
view
override
returns (uint256[5] memory)
{
uint256[5] memory result =
[
_totalSupply,
_balances[account],
rewardsDuration,
rewardRate.mul(rewardsDuration),
earned(account)
];
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Mutators
//////////////////////////////////////////////////////////////////////////////
function addAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_balances[account] = _balances[account].add(amount);
// Dispatch event
emit AssetAdded(account, amount, _balances[account]);
}
function removeAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_balances[account] = _balances[account].sub(amount);
// Dispatch event
emit AssetRemoved(account, amount, _balances[account]);
}
function addShares(address account, uint256 amount)
external
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
// Notify controller
controller.onDeposit(amount);
// Dispatch event
emit ShareAdded(account, amount);
}
function removeShares(address account, uint256 amount)
public
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
// Notify controller
controller.onWithdraw(amount);
// Dispatch event
emit ShareRemoved(account, amount);
}
function getReward(address account, address rewardRecipient)
public
override
onlyOwner
updateReward(account)
{
// Load state
uint256 reward = rewards[account];
if (reward > 0) {
// Update state
rewards[account] = 0;
availableRewards = availableRewards.sub(reward);
// Notify controller
controller.payOutRewards(rewardRecipient, reward);
// Dispatch event
emit RewardPaid(account, rewardRecipient, reward);
}
}
function exit(address account, address rewardRecipient)
external
override
onlyOwner
{
removeShares(account, _balances[account]);
getReward(account, rewardRecipient);
}
//////////////////////////////////////////////////////////////////////////////
// Restricted functions
//////////////////////////////////////////////////////////////////////////////
function setController(address newController)
external
override
onlyController
{
// Update state
controller = IController(newController);
// Dispatch event
emit ControllerChanged(newController);
}
function notifyRewardAmount(uint256 reward)
external
override
onlyController
updateReward(address(0))
{
// Update state
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
// solhint-disable-next-line not-rely-on-time
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
availableRewards = availableRewards.add(reward);
// Validate state
//
// Ensure the provided reward amount is not more than the balance in the
// contract.
//
// This keeps the reward rate in the right range, preventing overflows due
// to very high values of rewardRate in the earned and rewardsPerToken
// functions.
//
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
//
require(
rewardRate <= availableRewards.div(rewardsDuration),
'Provided reward too high'
);
// Update state
// solhint-disable-next-line not-rely-on-time
lastUpdateTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
periodFinish = block.timestamp.add(rewardsDuration);
// Dispatch event
emit RewardAdded(reward);
}
/**
* @dev We don't have any rebalancing here
*/
// solhint-disable-next-line no-empty-blocks
function rebalance() external override onlyController {}
/**
* @dev Added to support recovering LP Rewards from other systems to be
* distributed to holders
*/
function recoverERC20(
address recipient,
address tokenAddress,
uint256 tokenAmount
) external onlyController {
// Call ancestor
_recoverERC20(recipient, tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration)
external
override
onlyController
{
// Validate state
require(
// solhint-disable-next-line not-rely-on-time
periodFinish == 0 || block.timestamp > periodFinish,
'Reward period not finished'
);
// Update state
rewardsDuration = _rewardsDuration;
// Dispatch event
emit RewardsDurationUpdated(rewardsDuration);
}
} | /**
* @notice Farm is owned by a CFolio contract.
*
* All state modifing calls are only allowed from this owner.
*/ | NatSpecMultiLine | addAssets | function addAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_balances[account] = _balances[account].add(amount);
// Dispatch event
emit AssetAdded(account, amount, _balances[account]);
}
| ////////////////////////////////////////////////////////////////////////////// | NatSpecSingleLine | v0.7.4+commit.3f05b770 | Apache-2.0 | {
"func_code_index": [
4592,
4932
]
} | 158 |
|
CFolioFarm | contracts/src/investment/CFolioFarm.sol | 0xb18104e050f1e8e828dd2b0260f7feb1c2178752 | Solidity | CFolioFarm | contract CFolioFarm is IFarm, ICFolioFarm, Ownable, ERC20Recovery {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
uint256 public override periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 14 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 private availableRewards;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
// Unique name of this farm instance, used in controller
string private _farmName;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
// The address of the controller
IController public override controller;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
event RewardAdded(uint256 reward);
event AssetAdded(address indexed user, uint256 amount, uint256 totalAmount);
event AssetRemoved(address indexed user, uint256 amount, uint256 totalAmount);
event ShareAdded(address indexed user, uint256 amount);
event ShareRemoved(address indexed user, uint256 amount);
event RewardPaid(
address indexed account,
address indexed user,
uint256 reward
);
event RewardsDurationUpdated(uint256 newDuration);
event ControllerChanged(address newController);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyController {
require(_msgSender() == address(controller), 'not controller');
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
constructor(
address _owner,
string memory _name,
address _controller
) {
// Validate parameters
require(_owner != address(0), 'Invalid owner');
require(_controller != address(0), 'Invalid controller');
// Initialize {Ownable}
transferOwnership(_owner);
// Initialize state
_farmName = _name;
controller = IController(_controller);
}
//////////////////////////////////////////////////////////////////////////////
// Views
//////////////////////////////////////////////////////////////////////////////
function farmName() external view override returns (string memory) {
return _farmName;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return
_balances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
function getUIData(address account)
external
view
override
returns (uint256[5] memory)
{
uint256[5] memory result =
[
_totalSupply,
_balances[account],
rewardsDuration,
rewardRate.mul(rewardsDuration),
earned(account)
];
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Mutators
//////////////////////////////////////////////////////////////////////////////
function addAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_balances[account] = _balances[account].add(amount);
// Dispatch event
emit AssetAdded(account, amount, _balances[account]);
}
function removeAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_balances[account] = _balances[account].sub(amount);
// Dispatch event
emit AssetRemoved(account, amount, _balances[account]);
}
function addShares(address account, uint256 amount)
external
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
// Notify controller
controller.onDeposit(amount);
// Dispatch event
emit ShareAdded(account, amount);
}
function removeShares(address account, uint256 amount)
public
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
// Notify controller
controller.onWithdraw(amount);
// Dispatch event
emit ShareRemoved(account, amount);
}
function getReward(address account, address rewardRecipient)
public
override
onlyOwner
updateReward(account)
{
// Load state
uint256 reward = rewards[account];
if (reward > 0) {
// Update state
rewards[account] = 0;
availableRewards = availableRewards.sub(reward);
// Notify controller
controller.payOutRewards(rewardRecipient, reward);
// Dispatch event
emit RewardPaid(account, rewardRecipient, reward);
}
}
function exit(address account, address rewardRecipient)
external
override
onlyOwner
{
removeShares(account, _balances[account]);
getReward(account, rewardRecipient);
}
//////////////////////////////////////////////////////////////////////////////
// Restricted functions
//////////////////////////////////////////////////////////////////////////////
function setController(address newController)
external
override
onlyController
{
// Update state
controller = IController(newController);
// Dispatch event
emit ControllerChanged(newController);
}
function notifyRewardAmount(uint256 reward)
external
override
onlyController
updateReward(address(0))
{
// Update state
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
// solhint-disable-next-line not-rely-on-time
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
availableRewards = availableRewards.add(reward);
// Validate state
//
// Ensure the provided reward amount is not more than the balance in the
// contract.
//
// This keeps the reward rate in the right range, preventing overflows due
// to very high values of rewardRate in the earned and rewardsPerToken
// functions.
//
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
//
require(
rewardRate <= availableRewards.div(rewardsDuration),
'Provided reward too high'
);
// Update state
// solhint-disable-next-line not-rely-on-time
lastUpdateTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
periodFinish = block.timestamp.add(rewardsDuration);
// Dispatch event
emit RewardAdded(reward);
}
/**
* @dev We don't have any rebalancing here
*/
// solhint-disable-next-line no-empty-blocks
function rebalance() external override onlyController {}
/**
* @dev Added to support recovering LP Rewards from other systems to be
* distributed to holders
*/
function recoverERC20(
address recipient,
address tokenAddress,
uint256 tokenAmount
) external onlyController {
// Call ancestor
_recoverERC20(recipient, tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration)
external
override
onlyController
{
// Validate state
require(
// solhint-disable-next-line not-rely-on-time
periodFinish == 0 || block.timestamp > periodFinish,
'Reward period not finished'
);
// Update state
rewardsDuration = _rewardsDuration;
// Dispatch event
emit RewardsDurationUpdated(rewardsDuration);
}
} | /**
* @notice Farm is owned by a CFolio contract.
*
* All state modifing calls are only allowed from this owner.
*/ | NatSpecMultiLine | setController | function setController(address newController)
external
override
onlyController
{
// Update state
controller = IController(newController);
// Dispatch event
emit ControllerChanged(newController);
}
| ////////////////////////////////////////////////////////////////////////////// | NatSpecSingleLine | v0.7.4+commit.3f05b770 | Apache-2.0 | {
"func_code_index": [
7075,
7306
]
} | 159 |
|
CFolioFarm | contracts/src/investment/CFolioFarm.sol | 0xb18104e050f1e8e828dd2b0260f7feb1c2178752 | Solidity | CFolioFarm | contract CFolioFarm is IFarm, ICFolioFarm, Ownable, ERC20Recovery {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
uint256 public override periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 14 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 private availableRewards;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
// Unique name of this farm instance, used in controller
string private _farmName;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
// The address of the controller
IController public override controller;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
event RewardAdded(uint256 reward);
event AssetAdded(address indexed user, uint256 amount, uint256 totalAmount);
event AssetRemoved(address indexed user, uint256 amount, uint256 totalAmount);
event ShareAdded(address indexed user, uint256 amount);
event ShareRemoved(address indexed user, uint256 amount);
event RewardPaid(
address indexed account,
address indexed user,
uint256 reward
);
event RewardsDurationUpdated(uint256 newDuration);
event ControllerChanged(address newController);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyController {
require(_msgSender() == address(controller), 'not controller');
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
constructor(
address _owner,
string memory _name,
address _controller
) {
// Validate parameters
require(_owner != address(0), 'Invalid owner');
require(_controller != address(0), 'Invalid controller');
// Initialize {Ownable}
transferOwnership(_owner);
// Initialize state
_farmName = _name;
controller = IController(_controller);
}
//////////////////////////////////////////////////////////////////////////////
// Views
//////////////////////////////////////////////////////////////////////////////
function farmName() external view override returns (string memory) {
return _farmName;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return
_balances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
function getUIData(address account)
external
view
override
returns (uint256[5] memory)
{
uint256[5] memory result =
[
_totalSupply,
_balances[account],
rewardsDuration,
rewardRate.mul(rewardsDuration),
earned(account)
];
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Mutators
//////////////////////////////////////////////////////////////////////////////
function addAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_balances[account] = _balances[account].add(amount);
// Dispatch event
emit AssetAdded(account, amount, _balances[account]);
}
function removeAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_balances[account] = _balances[account].sub(amount);
// Dispatch event
emit AssetRemoved(account, amount, _balances[account]);
}
function addShares(address account, uint256 amount)
external
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
// Notify controller
controller.onDeposit(amount);
// Dispatch event
emit ShareAdded(account, amount);
}
function removeShares(address account, uint256 amount)
public
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
// Notify controller
controller.onWithdraw(amount);
// Dispatch event
emit ShareRemoved(account, amount);
}
function getReward(address account, address rewardRecipient)
public
override
onlyOwner
updateReward(account)
{
// Load state
uint256 reward = rewards[account];
if (reward > 0) {
// Update state
rewards[account] = 0;
availableRewards = availableRewards.sub(reward);
// Notify controller
controller.payOutRewards(rewardRecipient, reward);
// Dispatch event
emit RewardPaid(account, rewardRecipient, reward);
}
}
function exit(address account, address rewardRecipient)
external
override
onlyOwner
{
removeShares(account, _balances[account]);
getReward(account, rewardRecipient);
}
//////////////////////////////////////////////////////////////////////////////
// Restricted functions
//////////////////////////////////////////////////////////////////////////////
function setController(address newController)
external
override
onlyController
{
// Update state
controller = IController(newController);
// Dispatch event
emit ControllerChanged(newController);
}
function notifyRewardAmount(uint256 reward)
external
override
onlyController
updateReward(address(0))
{
// Update state
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
// solhint-disable-next-line not-rely-on-time
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
availableRewards = availableRewards.add(reward);
// Validate state
//
// Ensure the provided reward amount is not more than the balance in the
// contract.
//
// This keeps the reward rate in the right range, preventing overflows due
// to very high values of rewardRate in the earned and rewardsPerToken
// functions.
//
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
//
require(
rewardRate <= availableRewards.div(rewardsDuration),
'Provided reward too high'
);
// Update state
// solhint-disable-next-line not-rely-on-time
lastUpdateTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
periodFinish = block.timestamp.add(rewardsDuration);
// Dispatch event
emit RewardAdded(reward);
}
/**
* @dev We don't have any rebalancing here
*/
// solhint-disable-next-line no-empty-blocks
function rebalance() external override onlyController {}
/**
* @dev Added to support recovering LP Rewards from other systems to be
* distributed to holders
*/
function recoverERC20(
address recipient,
address tokenAddress,
uint256 tokenAmount
) external onlyController {
// Call ancestor
_recoverERC20(recipient, tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration)
external
override
onlyController
{
// Validate state
require(
// solhint-disable-next-line not-rely-on-time
periodFinish == 0 || block.timestamp > periodFinish,
'Reward period not finished'
);
// Update state
rewardsDuration = _rewardsDuration;
// Dispatch event
emit RewardsDurationUpdated(rewardsDuration);
}
} | /**
* @notice Farm is owned by a CFolio contract.
*
* All state modifing calls are only allowed from this owner.
*/ | NatSpecMultiLine | rebalance | function rebalance() external override onlyController {}
| // solhint-disable-next-line no-empty-blocks | LineComment | v0.7.4+commit.3f05b770 | Apache-2.0 | {
"func_code_index": [
8775,
8833
]
} | 160 |
|
CFolioFarm | contracts/src/investment/CFolioFarm.sol | 0xb18104e050f1e8e828dd2b0260f7feb1c2178752 | Solidity | CFolioFarm | contract CFolioFarm is IFarm, ICFolioFarm, Ownable, ERC20Recovery {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
uint256 public override periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 14 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 private availableRewards;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
// Unique name of this farm instance, used in controller
string private _farmName;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
// The address of the controller
IController public override controller;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
event RewardAdded(uint256 reward);
event AssetAdded(address indexed user, uint256 amount, uint256 totalAmount);
event AssetRemoved(address indexed user, uint256 amount, uint256 totalAmount);
event ShareAdded(address indexed user, uint256 amount);
event ShareRemoved(address indexed user, uint256 amount);
event RewardPaid(
address indexed account,
address indexed user,
uint256 reward
);
event RewardsDurationUpdated(uint256 newDuration);
event ControllerChanged(address newController);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyController {
require(_msgSender() == address(controller), 'not controller');
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
constructor(
address _owner,
string memory _name,
address _controller
) {
// Validate parameters
require(_owner != address(0), 'Invalid owner');
require(_controller != address(0), 'Invalid controller');
// Initialize {Ownable}
transferOwnership(_owner);
// Initialize state
_farmName = _name;
controller = IController(_controller);
}
//////////////////////////////////////////////////////////////////////////////
// Views
//////////////////////////////////////////////////////////////////////////////
function farmName() external view override returns (string memory) {
return _farmName;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return
_balances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
function getUIData(address account)
external
view
override
returns (uint256[5] memory)
{
uint256[5] memory result =
[
_totalSupply,
_balances[account],
rewardsDuration,
rewardRate.mul(rewardsDuration),
earned(account)
];
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Mutators
//////////////////////////////////////////////////////////////////////////////
function addAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_balances[account] = _balances[account].add(amount);
// Dispatch event
emit AssetAdded(account, amount, _balances[account]);
}
function removeAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_balances[account] = _balances[account].sub(amount);
// Dispatch event
emit AssetRemoved(account, amount, _balances[account]);
}
function addShares(address account, uint256 amount)
external
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
// Notify controller
controller.onDeposit(amount);
// Dispatch event
emit ShareAdded(account, amount);
}
function removeShares(address account, uint256 amount)
public
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
// Notify controller
controller.onWithdraw(amount);
// Dispatch event
emit ShareRemoved(account, amount);
}
function getReward(address account, address rewardRecipient)
public
override
onlyOwner
updateReward(account)
{
// Load state
uint256 reward = rewards[account];
if (reward > 0) {
// Update state
rewards[account] = 0;
availableRewards = availableRewards.sub(reward);
// Notify controller
controller.payOutRewards(rewardRecipient, reward);
// Dispatch event
emit RewardPaid(account, rewardRecipient, reward);
}
}
function exit(address account, address rewardRecipient)
external
override
onlyOwner
{
removeShares(account, _balances[account]);
getReward(account, rewardRecipient);
}
//////////////////////////////////////////////////////////////////////////////
// Restricted functions
//////////////////////////////////////////////////////////////////////////////
function setController(address newController)
external
override
onlyController
{
// Update state
controller = IController(newController);
// Dispatch event
emit ControllerChanged(newController);
}
function notifyRewardAmount(uint256 reward)
external
override
onlyController
updateReward(address(0))
{
// Update state
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
// solhint-disable-next-line not-rely-on-time
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
availableRewards = availableRewards.add(reward);
// Validate state
//
// Ensure the provided reward amount is not more than the balance in the
// contract.
//
// This keeps the reward rate in the right range, preventing overflows due
// to very high values of rewardRate in the earned and rewardsPerToken
// functions.
//
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
//
require(
rewardRate <= availableRewards.div(rewardsDuration),
'Provided reward too high'
);
// Update state
// solhint-disable-next-line not-rely-on-time
lastUpdateTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
periodFinish = block.timestamp.add(rewardsDuration);
// Dispatch event
emit RewardAdded(reward);
}
/**
* @dev We don't have any rebalancing here
*/
// solhint-disable-next-line no-empty-blocks
function rebalance() external override onlyController {}
/**
* @dev Added to support recovering LP Rewards from other systems to be
* distributed to holders
*/
function recoverERC20(
address recipient,
address tokenAddress,
uint256 tokenAmount
) external onlyController {
// Call ancestor
_recoverERC20(recipient, tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration)
external
override
onlyController
{
// Validate state
require(
// solhint-disable-next-line not-rely-on-time
periodFinish == 0 || block.timestamp > periodFinish,
'Reward period not finished'
);
// Update state
rewardsDuration = _rewardsDuration;
// Dispatch event
emit RewardsDurationUpdated(rewardsDuration);
}
} | /**
* @notice Farm is owned by a CFolio contract.
*
* All state modifing calls are only allowed from this owner.
*/ | NatSpecMultiLine | recoverERC20 | function recoverERC20(
address recipient,
address tokenAddress,
uint256 tokenAmount
) external onlyController {
// Call ancestor
_recoverERC20(recipient, tokenAddress, tokenAmount);
}
| /**
* @dev Added to support recovering LP Rewards from other systems to be
* distributed to holders
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | Apache-2.0 | {
"func_code_index": [
8949,
9158
]
} | 161 |
|
DANACHO | DANACHO.sol | 0x9256d3de679c96327dd0fca0b64f4b9de3ab95c5 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://b221d5a22ac6a46fa17293a69741cdf97babc1be9193bf47c942fbc806506981 | {
"func_code_index": [
642,
823
]
} | 162 |
DANACHO | DANACHO.sol | 0x9256d3de679c96327dd0fca0b64f4b9de3ab95c5 | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
//require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
// require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | transfer | function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
//require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://b221d5a22ac6a46fa17293a69741cdf97babc1be9193bf47c942fbc806506981 | {
"func_code_index": [
324,
737
]
} | 163 |
DANACHO | DANACHO.sol | 0x9256d3de679c96327dd0fca0b64f4b9de3ab95c5 | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
//require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
// require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://b221d5a22ac6a46fa17293a69741cdf97babc1be9193bf47c942fbc806506981 | {
"func_code_index": [
870,
991
]
} | 164 |
DANACHO | DANACHO.sol | 0x9256d3de679c96327dd0fca0b64f4b9de3ab95c5 | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
//require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
// require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
// require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| /**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://b221d5a22ac6a46fa17293a69741cdf97babc1be9193bf47c942fbc806506981 | {
"func_code_index": [
1339,
1949
]
} | 165 |
DANACHO | DANACHO.sol | 0x9256d3de679c96327dd0fca0b64f4b9de3ab95c5 | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
//require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
// require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | approve | function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://b221d5a22ac6a46fa17293a69741cdf97babc1be9193bf47c942fbc806506981 | {
"func_code_index": [
2581,
2791
]
} | 166 |
DANACHO | DANACHO.sol | 0x9256d3de679c96327dd0fca0b64f4b9de3ab95c5 | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
//require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
// require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | allowance | function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://b221d5a22ac6a46fa17293a69741cdf97babc1be9193bf47c942fbc806506981 | {
"func_code_index": [
3031,
3182
]
} | 167 |
DANACHO | DANACHO.sol | 0x9256d3de679c96327dd0fca0b64f4b9de3ab95c5 | Solidity | StandardToken | contract StandardToken is ERC20Basic, Ownable {
uint256 public totalSupply;
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool trans1) {
require(_to != address(0));
//require(canTransfer(msg.sender));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool trans) {
require(_to != address(0));
// require(canTransfer(msg.sender));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool hello) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
*/
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | increaseApproval | function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://b221d5a22ac6a46fa17293a69741cdf97babc1be9193bf47c942fbc806506981 | {
"func_code_index": [
3427,
3705
]
} | 168 |
DANACHO | DANACHO.sol | 0x9256d3de679c96327dd0fca0b64f4b9de3ab95c5 | Solidity | BurnableToken | contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
} | /**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/ | NatSpecMultiLine | burn | function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
| /**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | None | ipfs://b221d5a22ac6a46fa17293a69741cdf97babc1be9193bf47c942fbc806506981 | {
"func_code_index": [
225,
770
]
} | 169 |
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | Owned | contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be owner.
*/
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
} | // https://docs.synthetix.io/contracts/Owned | LineComment | nominateNewOwner | function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
| /**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
443,
585
]
} | 170 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | Owned | contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be owner.
*/
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
} | // https://docs.synthetix.io/contracts/Owned | LineComment | acceptOwnership | function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
| /**
* @notice Accept the nomination to be owner.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
653,
923
]
} | 171 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | State | contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _owner, address _associatedContract) public Owned(_owner) {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract {
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
} | // https://docs.synthetix.io/contracts/State | LineComment | setAssociatedContract | function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
| // Change the associated contract to a new address | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
487,
688
]
} | 172 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | EternalStorage | contract EternalStorage is State {
constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) UIntStorage;
mapping(bytes32 => string) StringStorage;
mapping(bytes32 => address) AddressStorage;
mapping(bytes32 => bytes) BytesStorage;
mapping(bytes32 => bytes32) Bytes32Storage;
mapping(bytes32 => bool) BooleanStorage;
mapping(bytes32 => int) IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
} | // https://docs.synthetix.io/contracts/EternalStorage | LineComment | getUIntValue | function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
| // UIntStorage; | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
519,
633
]
} | 173 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | EternalStorage | contract EternalStorage is State {
constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) UIntStorage;
mapping(bytes32 => string) StringStorage;
mapping(bytes32 => address) AddressStorage;
mapping(bytes32 => bytes) BytesStorage;
mapping(bytes32 => bytes32) Bytes32Storage;
mapping(bytes32 => bool) BooleanStorage;
mapping(bytes32 => int) IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
} | // https://docs.synthetix.io/contracts/EternalStorage | LineComment | getStringValue | function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
| // StringStorage | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
910,
1037
]
} | 174 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | EternalStorage | contract EternalStorage is State {
constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) UIntStorage;
mapping(bytes32 => string) StringStorage;
mapping(bytes32 => address) AddressStorage;
mapping(bytes32 => bytes) BytesStorage;
mapping(bytes32 => bytes32) Bytes32Storage;
mapping(bytes32 => bool) BooleanStorage;
mapping(bytes32 => int) IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
} | // https://docs.synthetix.io/contracts/EternalStorage | LineComment | getAddressValue | function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
| // AddressStorage | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
1325,
1448
]
} | 175 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | EternalStorage | contract EternalStorage is State {
constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) UIntStorage;
mapping(bytes32 => string) StringStorage;
mapping(bytes32 => address) AddressStorage;
mapping(bytes32 => bytes) BytesStorage;
mapping(bytes32 => bytes32) Bytes32Storage;
mapping(bytes32 => bool) BooleanStorage;
mapping(bytes32 => int) IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
} | // https://docs.synthetix.io/contracts/EternalStorage | LineComment | getBytesValue | function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
| // BytesStorage | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
1739,
1863
]
} | 176 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | EternalStorage | contract EternalStorage is State {
constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) UIntStorage;
mapping(bytes32 => string) StringStorage;
mapping(bytes32 => address) AddressStorage;
mapping(bytes32 => bytes) BytesStorage;
mapping(bytes32 => bytes32) Bytes32Storage;
mapping(bytes32 => bool) BooleanStorage;
mapping(bytes32 => int) IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
} | // https://docs.synthetix.io/contracts/EternalStorage | LineComment | getBytes32Value | function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
| // Bytes32Storage | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
2146,
2269
]
} | 177 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | EternalStorage | contract EternalStorage is State {
constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) UIntStorage;
mapping(bytes32 => string) StringStorage;
mapping(bytes32 => address) AddressStorage;
mapping(bytes32 => bytes) BytesStorage;
mapping(bytes32 => bytes32) Bytes32Storage;
mapping(bytes32 => bool) BooleanStorage;
mapping(bytes32 => int) IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
} | // https://docs.synthetix.io/contracts/EternalStorage | LineComment | getBooleanValue | function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
| // BooleanStorage | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
2562,
2682
]
} | 178 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | EternalStorage | contract EternalStorage is State {
constructor(address _owner, address _associatedContract) public State(_owner, _associatedContract) {}
/* ========== DATA TYPES ========== */
mapping(bytes32 => uint) UIntStorage;
mapping(bytes32 => string) StringStorage;
mapping(bytes32 => address) AddressStorage;
mapping(bytes32 => bytes) BytesStorage;
mapping(bytes32 => bytes32) Bytes32Storage;
mapping(bytes32 => bool) BooleanStorage;
mapping(bytes32 => int) IntStorage;
// UIntStorage;
function getUIntValue(bytes32 record) external view returns (uint) {
return UIntStorage[record];
}
function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract {
UIntStorage[record] = value;
}
function deleteUIntValue(bytes32 record) external onlyAssociatedContract {
delete UIntStorage[record];
}
// StringStorage
function getStringValue(bytes32 record) external view returns (string memory) {
return StringStorage[record];
}
function setStringValue(bytes32 record, string value) external onlyAssociatedContract {
StringStorage[record] = value;
}
function deleteStringValue(bytes32 record) external onlyAssociatedContract {
delete StringStorage[record];
}
// AddressStorage
function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
function setAddressValue(bytes32 record, address value) external onlyAssociatedContract {
AddressStorage[record] = value;
}
function deleteAddressValue(bytes32 record) external onlyAssociatedContract {
delete AddressStorage[record];
}
// BytesStorage
function getBytesValue(bytes32 record) external view returns (bytes memory) {
return BytesStorage[record];
}
function setBytesValue(bytes32 record, bytes value) external onlyAssociatedContract {
BytesStorage[record] = value;
}
function deleteBytesValue(bytes32 record) external onlyAssociatedContract {
delete BytesStorage[record];
}
// Bytes32Storage
function getBytes32Value(bytes32 record) external view returns (bytes32) {
return Bytes32Storage[record];
}
function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract {
Bytes32Storage[record] = value;
}
function deleteBytes32Value(bytes32 record) external onlyAssociatedContract {
delete Bytes32Storage[record];
}
// BooleanStorage
function getBooleanValue(bytes32 record) external view returns (bool) {
return BooleanStorage[record];
}
function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract {
BooleanStorage[record] = value;
}
function deleteBooleanValue(bytes32 record) external onlyAssociatedContract {
delete BooleanStorage[record];
}
// IntStorage
function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
function setIntValue(bytes32 record, int value) external onlyAssociatedContract {
IntStorage[record] = value;
}
function deleteIntValue(bytes32 record) external onlyAssociatedContract {
delete IntStorage[record];
}
} | // https://docs.synthetix.io/contracts/EternalStorage | LineComment | getIntValue | function getIntValue(bytes32 record) external view returns (int) {
return IntStorage[record];
}
| // IntStorage | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
2968,
3079
]
} | 179 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | _getKey | function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
| // Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
1118,
1312
]
} | 180 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | canBurnFor | function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
| // hash of actionName + address of authoriser + address for the delegate | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
1391,
1560
]
} | 181 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | _checkApproval | function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
| // internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
2435,
2700
]
} | 182 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | approveAllDelegatePowers | function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
| // Approve All | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
2762,
2891
]
} | 183 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | removeAllDelegatePowers | function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
| // Removes all delegate approvals | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
2931,
3157
]
} | 184 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | approveBurnOnBehalf | function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
| // Burn on behalf | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
3181,
3310
]
} | 185 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | approveIssueOnBehalf | function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
| // Issue on behalf | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
3470,
3601
]
} | 186 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | approveClaimOnBehalf | function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
| // Claim on behalf | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
3763,
3894
]
} | 187 |
||
DelegateApprovals | DelegateApprovals.sol | 0x15fd6e554874b9e70f832ed37f231ac5e142362f | Solidity | DelegateApprovals | contract DelegateApprovals is Owned {
bytes32 public constant BURN_FOR_ADDRESS = "BurnForAddress";
bytes32 public constant ISSUE_FOR_ADDRESS = "IssueForAddress";
bytes32 public constant CLAIM_FOR_ADDRESS = "ClaimForAddress";
bytes32 public constant EXCHANGE_FOR_ADDRESS = "ExchangeForAddress";
bytes32 public constant APPROVE_ALL = "ApproveAll";
bytes32[5] private _delegatableFunctions = [
APPROVE_ALL,
BURN_FOR_ADDRESS,
ISSUE_FOR_ADDRESS,
CLAIM_FOR_ADDRESS,
EXCHANGE_FOR_ADDRESS
];
/* ========== STATE VARIABLES ========== */
EternalStorage public eternalStorage;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _eternalStorage The eternalStorage address.
*/
constructor(address _owner, EternalStorage _eternalStorage) public Owned(_owner) {
eternalStorage = _eternalStorage;
}
/* ========== VIEWS ========== */
// Move it to setter and associatedState
// util to get key based on action name + address of authoriser + address for delegate
function _getKey(bytes32 _action, address _authoriser, address _delegate) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_action, _authoriser, _delegate));
}
// hash of actionName + address of authoriser + address for the delegate
function canBurnFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(BURN_FOR_ADDRESS, authoriser, delegate);
}
function canIssueFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(ISSUE_FOR_ADDRESS, authoriser, delegate);
}
function canClaimFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(CLAIM_FOR_ADDRESS, authoriser, delegate);
}
function canExchangeFor(address authoriser, address delegate) external view returns (bool) {
return _checkApproval(EXCHANGE_FOR_ADDRESS, authoriser, delegate);
}
function approvedAll(address authoriser, address delegate) public view returns (bool) {
return eternalStorage.getBooleanValue(_getKey(APPROVE_ALL, authoriser, delegate));
}
// internal function to check approval based on action
// if approved for all actions then will return true
// before checking specific approvals
function _checkApproval(bytes32 action, address authoriser, address delegate) internal view returns (bool) {
if (approvedAll(authoriser, delegate)) return true;
return eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate));
}
/* ========== SETTERS ========== */
// Approve All
function approveAllDelegatePowers(address delegate) external {
_setApproval(APPROVE_ALL, msg.sender, delegate);
}
// Removes all delegate approvals
function removeAllDelegatePowers(address delegate) external {
for (uint i = 0; i < _delegatableFunctions.length; i++) {
_withdrawApproval(_delegatableFunctions[i], msg.sender, delegate);
}
}
// Burn on behalf
function approveBurnOnBehalf(address delegate) external {
_setApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
function removeBurnOnBehalf(address delegate) external {
_withdrawApproval(BURN_FOR_ADDRESS, msg.sender, delegate);
}
// Issue on behalf
function approveIssueOnBehalf(address delegate) external {
_setApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
function removeIssueOnBehalf(address delegate) external {
_withdrawApproval(ISSUE_FOR_ADDRESS, msg.sender, delegate);
}
// Claim on behalf
function approveClaimOnBehalf(address delegate) external {
_setApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
function removeClaimOnBehalf(address delegate) external {
_withdrawApproval(CLAIM_FOR_ADDRESS, msg.sender, delegate);
}
// Exchange on behalf
function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function removeExchangeOnBehalf(address delegate) external {
_withdrawApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
function _setApproval(bytes32 action, address authoriser, address delegate) internal {
require(delegate != address(0), "Can't delegate to address(0)");
eternalStorage.setBooleanValue(_getKey(action, authoriser, delegate), true);
emit Approval(authoriser, delegate, action);
}
function _withdrawApproval(bytes32 action, address authoriser, address delegate) internal {
// Check approval is set otherwise skip deleting approval
if (eternalStorage.getBooleanValue(_getKey(action, authoriser, delegate))) {
eternalStorage.deleteBooleanValue(_getKey(action, authoriser, delegate));
emit WithdrawApproval(authoriser, delegate, action);
}
}
function setEternalStorage(EternalStorage _eternalStorage) external onlyOwner {
require(_eternalStorage != address(0), "Can't set eternalStorage to address(0)");
eternalStorage = _eternalStorage;
emit EternalStorageUpdated(eternalStorage);
}
/* ========== EVENTS ========== */
event Approval(address indexed authoriser, address delegate, bytes32 action);
event WithdrawApproval(address indexed authoriser, address delegate, bytes32 action);
event EternalStorageUpdated(address newEternalStorage);
} | // https://docs.synthetix.io/contracts/DelegateApprovals | LineComment | approveExchangeOnBehalf | function approveExchangeOnBehalf(address delegate) external {
_setApproval(EXCHANGE_FOR_ADDRESS, msg.sender, delegate);
}
| // Exchange on behalf | LineComment | v0.4.25+commit.59dbf8f1 | {
"func_code_index": [
4059,
4196
]
} | 188 |
||
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | Owned | contract Owned {
/* Адрес владельца контракта*/
address owner;
/* Конструктор контракта, вызывается при первом запуске */
function Owned() {
owner = msg.sender;
}
/* Изменить владельца контракта, newOwner - адрес нового владельца */
function changeOwner(address newOwner) onlyowner {
owner = newOwner;
}
/* Модификатор для ограничения доступа к функциям только для владельца */
modifier onlyowner() {
if (msg.sender==owner) _;
}
/* Удалить контракт */
function kill() onlyowner {
if (msg.sender == owner) suicide(owner);
}
} | /* Родительский контракт */ | Comment | Owned | function Owned() {
owner = msg.sender;
}
| /* Конструктор контракта, вызывается при первом запуске */ | Comment | v0.4.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
142,
201
]
} | 189 |
|
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | Owned | contract Owned {
/* Адрес владельца контракта*/
address owner;
/* Конструктор контракта, вызывается при первом запуске */
function Owned() {
owner = msg.sender;
}
/* Изменить владельца контракта, newOwner - адрес нового владельца */
function changeOwner(address newOwner) onlyowner {
owner = newOwner;
}
/* Модификатор для ограничения доступа к функциям только для владельца */
modifier onlyowner() {
if (msg.sender==owner) _;
}
/* Удалить контракт */
function kill() onlyowner {
if (msg.sender == owner) suicide(owner);
}
} | /* Родительский контракт */ | Comment | changeOwner | function changeOwner(address newOwner) onlyowner {
owner = newOwner;
}
| /* Изменить владельца контракта, newOwner - адрес нового владельца */ | Comment | v0.4.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
279,
368
]
} | 190 |
|
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | Owned | contract Owned {
/* Адрес владельца контракта*/
address owner;
/* Конструктор контракта, вызывается при первом запуске */
function Owned() {
owner = msg.sender;
}
/* Изменить владельца контракта, newOwner - адрес нового владельца */
function changeOwner(address newOwner) onlyowner {
owner = newOwner;
}
/* Модификатор для ограничения доступа к функциям только для владельца */
modifier onlyowner() {
if (msg.sender==owner) _;
}
/* Удалить контракт */
function kill() onlyowner {
if (msg.sender == owner) suicide(owner);
}
} | /* Родительский контракт */ | Comment | kill | function kill() onlyowner {
if (msg.sender == owner) suicide(owner);
}
| /* Удалить контракт */ | Comment | v0.4.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
550,
639
]
} | 191 |
|
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | Token | contract Token is Owned {
/// Общее кол-во токенов
uint256 public totalSupply;
/// @param _owner адрес, с которого будет получен баланс
/// @return Баланс
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `msg.sender`
/// @param _to Адрес получателя
/// @param _value Кол-во токенов для отправки
/// @return Была ли отправка успешной или нет
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `_from` при условии что это подтверждено отправителем `_from`
/// @param _from Адрес отправителя
/// @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` подтверждает что с адреса `_spender` спишется `_value` токенов
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @param _value Кол-во токенов к подтверждению для отправки
/// @return Было ли подтверждение успешным или нет
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner Адрес аккаунта владеющего токенами
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @return Кол-во оставшихся токенов разрешённых для отправки
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);
} | // Абстрактный контракт для токена стандарта ERC 20
// https://github.com/ethereum/EIPs/issues/20 | LineComment | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance);
| /// @param _owner адрес, с которого будет получен баланс
/// @return Баланс | NatSpecSingleLine | v0.4.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
180,
255
]
} | 192 |
|
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | Token | contract Token is Owned {
/// Общее кол-во токенов
uint256 public totalSupply;
/// @param _owner адрес, с которого будет получен баланс
/// @return Баланс
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `msg.sender`
/// @param _to Адрес получателя
/// @param _value Кол-во токенов для отправки
/// @return Была ли отправка успешной или нет
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `_from` при условии что это подтверждено отправителем `_from`
/// @param _from Адрес отправителя
/// @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` подтверждает что с адреса `_spender` спишется `_value` токенов
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @param _value Кол-во токенов к подтверждению для отправки
/// @return Было ли подтверждение успешным или нет
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner Адрес аккаунта владеющего токенами
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @return Кол-во оставшихся токенов разрешённых для отправки
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);
} | // Абстрактный контракт для токена стандарта ERC 20
// https://github.com/ethereum/EIPs/issues/20 | LineComment | transfer | function transfer(address _to, uint256 _value) returns (bool success);
| /// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `msg.sender`
/// @param _to Адрес получателя
/// @param _value Кол-во токенов для отправки
/// @return Была ли отправка успешной или нет | NatSpecSingleLine | v0.4.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
485,
560
]
} | 193 |
|
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | Token | contract Token is Owned {
/// Общее кол-во токенов
uint256 public totalSupply;
/// @param _owner адрес, с которого будет получен баланс
/// @return Баланс
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `msg.sender`
/// @param _to Адрес получателя
/// @param _value Кол-во токенов для отправки
/// @return Была ли отправка успешной или нет
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `_from` при условии что это подтверждено отправителем `_from`
/// @param _from Адрес отправителя
/// @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` подтверждает что с адреса `_spender` спишется `_value` токенов
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @param _value Кол-во токенов к подтверждению для отправки
/// @return Было ли подтверждение успешным или нет
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner Адрес аккаунта владеющего токенами
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @return Кол-во оставшихся токенов разрешённых для отправки
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);
} | // Абстрактный контракт для токена стандарта ERC 20
// https://github.com/ethereum/EIPs/issues/20 | LineComment | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
| /// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `_from` при условии что это подтверждено отправителем `_from`
/// @param _from Адрес отправителя
/// @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.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
910,
1004
]
} | 194 |
|
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | Token | contract Token is Owned {
/// Общее кол-во токенов
uint256 public totalSupply;
/// @param _owner адрес, с которого будет получен баланс
/// @return Баланс
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `msg.sender`
/// @param _to Адрес получателя
/// @param _value Кол-во токенов для отправки
/// @return Была ли отправка успешной или нет
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `_from` при условии что это подтверждено отправителем `_from`
/// @param _from Адрес отправителя
/// @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` подтверждает что с адреса `_spender` спишется `_value` токенов
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @param _value Кол-во токенов к подтверждению для отправки
/// @return Было ли подтверждение успешным или нет
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner Адрес аккаунта владеющего токенами
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @return Кол-во оставшихся токенов разрешённых для отправки
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);
} | // Абстрактный контракт для токена стандарта ERC 20
// https://github.com/ethereum/EIPs/issues/20 | LineComment | approve | function approve(address _spender, uint256 _value) returns (bool success);
| /// @notice Вызывающий функции `msg.sender` подтверждает что с адреса `_spender` спишется `_value` токенов
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @param _value Кол-во токенов к подтверждению для отправки
/// @return Было ли подтверждение успешным или нет | NatSpecSingleLine | v0.4.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
1318,
1397
]
} | 195 |
|
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | Token | contract Token is Owned {
/// Общее кол-во токенов
uint256 public totalSupply;
/// @param _owner адрес, с которого будет получен баланс
/// @return Баланс
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `msg.sender`
/// @param _to Адрес получателя
/// @param _value Кол-во токенов для отправки
/// @return Была ли отправка успешной или нет
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice Отправить кол-во `_value` токенов на адрес `_to` с адреса `_from` при условии что это подтверждено отправителем `_from`
/// @param _from Адрес отправителя
/// @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` подтверждает что с адреса `_spender` спишется `_value` токенов
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @param _value Кол-во токенов к подтверждению для отправки
/// @return Было ли подтверждение успешным или нет
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner Адрес аккаунта владеющего токенами
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @return Кол-во оставшихся токенов разрешённых для отправки
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);
} | // Абстрактный контракт для токена стандарта ERC 20
// https://github.com/ethereum/EIPs/issues/20 | LineComment | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining);
| /// @param _owner Адрес аккаунта владеющего токенами
/// @param _spender Адрес аккаунта, с которого возможно списать токены
/// @return Кол-во оставшихся токенов разрешённых для отправки | NatSpecSingleLine | v0.4.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
1602,
1697
]
} | 196 |
|
BlackSnail | BlackSnail.sol | 0xfe17e67e1b2a69c24a4643442185ec821be0643a | Solidity | BlackSnail | contract BlackSnail is ERC20Token
{
function ()
{
// Если кто то пытается отправить эфир на адрес контракта, то будет вызвана ошибка.
throw;
}
/* Публичные переменные токена */
string public name; // Название
uint8 public decimals; // Сколько десятичных знаков
string public symbol; // Идентификатор (трехбуквенный обычно)
string public version = '1.0'; // Версия
function BlackSnail(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol)
{
balances[msg.sender] = _initialAmount; // Передача создателю всех выпущенных монет
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
} | /* Основной контракт токена, наследует ERC20Token */ | Comment | BlackSnail | function BlackSnail(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol)
{
balances[msg.sender] = _initialAmount; // Передача создателю всех выпущенных монет
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
| // Версия | LineComment | v0.4.13+commit.fb4cb1a | bzzr://a6ea5b206aa0c5d0c21fe7b31ef1d139aa70f0c650be1bbb25ce22ccd163880f | {
"func_code_index": [
478,
881
]
} | 197 |
|
EasyAuction | contracts/EasyAuction.sol | 0x0b7ffc1f4ad541a4ed16b40d8c37f0929158d101 | Solidity | EasyAuction | contract EasyAuction is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint64;
using SafeMath for uint96;
using SafeMath for uint256;
using SafeCast for uint256;
using IterableOrderedOrderSet for IterableOrderedOrderSet.Data;
using IterableOrderedOrderSet for bytes32;
using IdToAddressBiMap for IdToAddressBiMap.Data;
modifier atStageOrderPlacement(uint256 auctionId) {
require(
block.timestamp < auctionData[auctionId].auctionEndDate,
"no longer in order placement phase"
);
_;
}
modifier atStageOrderPlacementAndCancelation(uint256 auctionId) {
require(
block.timestamp < auctionData[auctionId].orderCancellationEndDate,
"no longer in order placement and cancelation phase"
);
_;
}
modifier atStageSolutionSubmission(uint256 auctionId) {
{
uint256 auctionEndDate = auctionData[auctionId].auctionEndDate;
require(
auctionEndDate != 0 &&
block.timestamp >= auctionEndDate &&
auctionData[auctionId].clearingPriceOrder == bytes32(0),
"Auction not in solution submission phase"
);
}
_;
}
modifier atStageFinished(uint256 auctionId) {
require(
auctionData[auctionId].clearingPriceOrder != bytes32(0),
"Auction not yet finished"
);
_;
}
event NewSellOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event CancellationSellOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event ClaimedFromOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event NewUser(uint64 indexed userId, address indexed userAddress);
event NewAuction(
uint256 indexed auctionId,
IERC20 indexed _auctioningToken,
IERC20 indexed _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint64 userId,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
address allowListContract,
bytes allowListData
);
event AuctionCleared(
uint256 indexed auctionId,
uint96 soldAuctioningTokens,
uint96 soldBiddingTokens,
bytes32 clearingPriceOrder
);
event UserRegistration(address indexed user, uint64 userId);
struct AuctionData {
IERC20 auctioningToken;
IERC20 biddingToken;
uint256 orderCancellationEndDate;
uint256 auctionEndDate;
bytes32 initialAuctionOrder;
uint256 minimumBiddingAmountPerOrder;
uint256 interimSumBidAmount;
bytes32 interimOrder;
bytes32 clearingPriceOrder;
uint96 volumeClearingPriceOrder;
bool minFundingThresholdNotReached;
bool isAtomicClosureAllowed;
uint256 feeNumerator;
uint256 minFundingThreshold;
}
mapping(uint256 => IterableOrderedOrderSet.Data) internal sellOrders;
mapping(uint256 => AuctionData) public auctionData;
mapping(uint256 => address) public auctionAccessManager;
mapping(uint256 => bytes) public auctionAccessData;
IdToAddressBiMap.Data private registeredUsers;
uint64 public numUsers;
uint256 public auctionCounter;
constructor() public Ownable() {}
uint256 public feeNumerator = 0;
uint256 public constant FEE_DENOMINATOR = 1000;
uint64 public feeReceiverUserId = 1;
function setFeeParameters(
uint256 newFeeNumerator,
address newfeeReceiverAddress
) public onlyOwner() {
require(
newFeeNumerator <= 15,
"Fee is not allowed to be set higher than 1.5%"
);
// caution: for currently running auctions, the feeReceiverUserId is changing as well.
feeReceiverUserId = getUserId(newfeeReceiverAddress);
feeNumerator = newFeeNumerator;
}
// @dev: function to intiate a new auction
// Warning: In case the auction is expected to raise more than
// 2^96 units of the biddingToken, don't start the auction, as
// it will not be settlable. This corresponds to about 79
// billion DAI.
//
// Prices between biddingToken and auctioningToken are expressed by a
// fraction whose components are stored as uint96.
function initiateAuction(
IERC20 _auctioningToken,
IERC20 _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
bool isAtomicClosureAllowed,
address accessManagerContract,
bytes memory accessManagerContractData
) public returns (uint256) {
// withdraws sellAmount + fees
_auctioningToken.safeTransferFrom(
msg.sender,
address(this),
_auctionedSellAmount.mul(FEE_DENOMINATOR.add(feeNumerator)).div(
FEE_DENOMINATOR
) //[0]
);
require(_auctionedSellAmount > 0, "cannot auction zero tokens");
require(_minBuyAmount > 0, "tokens cannot be auctioned for free");
require(
minimumBiddingAmountPerOrder > 0,
"minimumBiddingAmountPerOrder is not allowed to be zero"
);
require(
orderCancellationEndDate <= auctionEndDate,
"time periods are not configured correctly"
);
require(
auctionEndDate > block.timestamp,
"auction end date must be in the future"
);
auctionCounter = auctionCounter.add(1);
sellOrders[auctionCounter].initializeEmptyList();
uint64 userId = getUserId(msg.sender);
auctionData[auctionCounter] = AuctionData(
_auctioningToken,
_biddingToken,
orderCancellationEndDate,
auctionEndDate,
IterableOrderedOrderSet.encodeOrder(
userId,
_minBuyAmount,
_auctionedSellAmount
),
minimumBiddingAmountPerOrder,
0,
IterableOrderedOrderSet.QUEUE_START,
bytes32(0),
0,
false,
isAtomicClosureAllowed,
feeNumerator,
minFundingThreshold
);
auctionAccessManager[auctionCounter] = accessManagerContract;
auctionAccessData[auctionCounter] = accessManagerContractData;
emit NewAuction(
auctionCounter,
_auctioningToken,
_biddingToken,
orderCancellationEndDate,
auctionEndDate,
userId,
_auctionedSellAmount,
_minBuyAmount,
minimumBiddingAmountPerOrder,
minFundingThreshold,
accessManagerContract,
accessManagerContractData
);
return auctionCounter;
}
function placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData
) external atStageOrderPlacement(auctionId) returns (uint64 userId) {
return
_placeSellOrders(
auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
allowListCallData,
msg.sender
);
}
function placeSellOrdersOnBehalf(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData,
address orderSubmitter
) external atStageOrderPlacement(auctionId) returns (uint64 userId) {
return
_placeSellOrders(
auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
allowListCallData,
orderSubmitter
);
}
function _placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData,
address orderSubmitter
) internal returns (uint64 userId) {
{
address allowListManger = auctionAccessManager[auctionId];
if (allowListManger != address(0)) {
require(
AllowListVerifier(allowListManger).isAllowed(
orderSubmitter,
auctionId,
allowListCallData
) == AllowListVerifierHelper.MAGICVALUE,
"user not allowed to place order"
);
}
}
{
(
,
uint96 buyAmountOfInitialAuctionOrder,
uint96 sellAmountOfInitialAuctionOrder
) = auctionData[auctionId].initialAuctionOrder.decodeOrder();
for (uint256 i = 0; i < _minBuyAmounts.length; i++) {
require(
_minBuyAmounts[i].mul(buyAmountOfInitialAuctionOrder) <
sellAmountOfInitialAuctionOrder.mul(_sellAmounts[i]),
"limit price not better than mimimal offer"
);
}
}
uint256 sumOfSellAmounts = 0;
userId = getUserId(orderSubmitter);
uint256 minimumBiddingAmountPerOrder =
auctionData[auctionId].minimumBiddingAmountPerOrder;
for (uint256 i = 0; i < _minBuyAmounts.length; i++) {
require(
_minBuyAmounts[i] > 0,
"_minBuyAmounts must be greater than 0"
);
// orders should have a minimum bid size in order to limit the gas
// required to compute the final price of the auction.
require(
_sellAmounts[i] > minimumBiddingAmountPerOrder,
"order too small"
);
if (
sellOrders[auctionId].insert(
IterableOrderedOrderSet.encodeOrder(
userId,
_minBuyAmounts[i],
_sellAmounts[i]
),
_prevSellOrders[i]
)
) {
sumOfSellAmounts = sumOfSellAmounts.add(_sellAmounts[i]);
emit NewSellOrder(
auctionId,
userId,
_minBuyAmounts[i],
_sellAmounts[i]
);
}
}
auctionData[auctionId].biddingToken.safeTransferFrom(
msg.sender,
address(this),
sumOfSellAmounts
); //[1]
}
function cancelSellOrders(uint256 auctionId, bytes32[] memory _sellOrders)
public
atStageOrderPlacementAndCancelation(auctionId)
{
uint64 userId = getUserId(msg.sender);
uint256 claimableAmount = 0;
for (uint256 i = 0; i < _sellOrders.length; i++) {
// Note: we keep the back pointer of the deleted element so that
// it can be used as a reference point to insert a new node.
bool success =
sellOrders[auctionId].removeKeepHistory(_sellOrders[i]);
if (success) {
(
uint64 userIdOfIter,
uint96 buyAmountOfIter,
uint96 sellAmountOfIter
) = _sellOrders[i].decodeOrder();
require(
userIdOfIter == userId,
"Only the user can cancel his orders"
);
claimableAmount = claimableAmount.add(sellAmountOfIter);
emit CancellationSellOrder(
auctionId,
userId,
buyAmountOfIter,
sellAmountOfIter
);
}
}
auctionData[auctionId].biddingToken.safeTransfer(
msg.sender,
claimableAmount
); //[2]
}
function precalculateSellAmountSum(
uint256 auctionId,
uint256 iterationSteps
) public atStageSolutionSubmission(auctionId) {
(, , uint96 auctioneerSellAmount) =
auctionData[auctionId].initialAuctionOrder.decodeOrder();
uint256 sumBidAmount = auctionData[auctionId].interimSumBidAmount;
bytes32 iterOrder = auctionData[auctionId].interimOrder;
for (uint256 i = 0; i < iterationSteps; i++) {
iterOrder = sellOrders[auctionId].next(iterOrder);
(, , uint96 sellAmountOfIter) = iterOrder.decodeOrder();
sumBidAmount = sumBidAmount.add(sellAmountOfIter);
}
require(
iterOrder != IterableOrderedOrderSet.QUEUE_END,
"reached end of order list"
);
// it is checked that not too many iteration steps were taken:
// require that the sum of SellAmounts times the price of the last order
// is not more than initially sold amount
(, uint96 buyAmountOfIter, uint96 sellAmountOfIter) =
iterOrder.decodeOrder();
require(
sumBidAmount.mul(buyAmountOfIter) <
auctioneerSellAmount.mul(sellAmountOfIter),
"too many orders summed up"
);
auctionData[auctionId].interimSumBidAmount = sumBidAmount;
auctionData[auctionId].interimOrder = iterOrder;
}
function settleAuctionAtomically(
uint256 auctionId,
uint96[] memory _minBuyAmount,
uint96[] memory _sellAmount,
bytes32[] memory _prevSellOrder,
bytes calldata allowListCallData
) public atStageSolutionSubmission(auctionId) {
require(
auctionData[auctionId].isAtomicClosureAllowed,
"not allowed to settle auction atomically"
);
require(
_minBuyAmount.length == 1 && _sellAmount.length == 1,
"Only one order can be placed atomically"
);
uint64 userId = getUserId(msg.sender);
require(
auctionData[auctionId].interimOrder.smallerThan(
IterableOrderedOrderSet.encodeOrder(
userId,
_minBuyAmount[0],
_sellAmount[0]
)
),
"precalculateSellAmountSum is already too advanced"
);
_placeSellOrders(
auctionId,
_minBuyAmount,
_sellAmount,
_prevSellOrder,
allowListCallData,
msg.sender
);
settleAuction(auctionId);
}
// @dev function settling the auction and calculating the price
function settleAuction(uint256 auctionId)
public
atStageSolutionSubmission(auctionId)
returns (bytes32 clearingOrder)
{
(
uint64 auctioneerId,
uint96 minAuctionedBuyAmount,
uint96 fullAuctionedAmount
) = auctionData[auctionId].initialAuctionOrder.decodeOrder();
uint256 currentBidSum = auctionData[auctionId].interimSumBidAmount;
bytes32 currentOrder = auctionData[auctionId].interimOrder;
uint256 buyAmountOfIter;
uint256 sellAmountOfIter;
uint96 fillVolumeOfAuctioneerOrder = fullAuctionedAmount;
// Sum order up, until fullAuctionedAmount is fully bought or queue end is reached
do {
bytes32 nextOrder = sellOrders[auctionId].next(currentOrder);
if (nextOrder == IterableOrderedOrderSet.QUEUE_END) {
break;
}
currentOrder = nextOrder;
(, buyAmountOfIter, sellAmountOfIter) = currentOrder.decodeOrder();
currentBidSum = currentBidSum.add(sellAmountOfIter);
} while (
currentBidSum.mul(buyAmountOfIter) <
fullAuctionedAmount.mul(sellAmountOfIter)
);
if (
currentBidSum > 0 &&
currentBidSum.mul(buyAmountOfIter) >=
fullAuctionedAmount.mul(sellAmountOfIter)
) {
// All considered/summed orders are sufficient to close the auction fully
// at price between current and previous orders.
uint256 uncoveredBids =
currentBidSum.sub(
fullAuctionedAmount.mul(sellAmountOfIter).div(
buyAmountOfIter
)
);
if (sellAmountOfIter >= uncoveredBids) {
//[13]
// Auction fully filled via partial match of currentOrder
uint256 sellAmountClearingOrder =
sellAmountOfIter.sub(uncoveredBids);
auctionData[auctionId]
.volumeClearingPriceOrder = sellAmountClearingOrder
.toUint96();
currentBidSum = currentBidSum.sub(uncoveredBids);
clearingOrder = currentOrder;
} else {
//[14]
// Auction fully filled via price strictly between currentOrder and the order
// immediately before. For a proof, see the security-considerations.md
currentBidSum = currentBidSum.sub(sellAmountOfIter);
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
currentBidSum.toUint96()
);
}
} else {
// All considered/summed orders are not sufficient to close the auction fully at price of last order //[18]
// Either a higher price must be used or auction is only partially filled
if (currentBidSum > minAuctionedBuyAmount) {
//[15]
// Price higher than last order would fill the auction
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
currentBidSum.toUint96()
);
} else {
//[16]
// Even at the initial auction price, the auction is partially filled
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
minAuctionedBuyAmount
);
fillVolumeOfAuctioneerOrder = currentBidSum
.mul(fullAuctionedAmount)
.div(minAuctionedBuyAmount)
.toUint96();
}
}
auctionData[auctionId].clearingPriceOrder = clearingOrder;
if (auctionData[auctionId].minFundingThreshold > currentBidSum) {
auctionData[auctionId].minFundingThresholdNotReached = true;
}
processFeesAndAuctioneerFunds(
auctionId,
fillVolumeOfAuctioneerOrder,
auctioneerId,
fullAuctionedAmount
);
emit AuctionCleared(
auctionId,
fillVolumeOfAuctioneerOrder,
uint96(currentBidSum),
clearingOrder
);
// Gas refunds
auctionAccessManager[auctionId] = address(0);
delete auctionAccessData[auctionId];
auctionData[auctionId].initialAuctionOrder = bytes32(0);
auctionData[auctionId].interimOrder = bytes32(0);
auctionData[auctionId].interimSumBidAmount = uint256(0);
auctionData[auctionId].minimumBiddingAmountPerOrder = uint256(0);
}
function claimFromParticipantOrder(
uint256 auctionId,
bytes32[] memory orders
)
public
atStageFinished(auctionId)
returns (
uint256 sumAuctioningTokenAmount,
uint256 sumBiddingTokenAmount
)
{
for (uint256 i = 0; i < orders.length; i++) {
// Note: we don't need to keep any information about the node since
// no new elements need to be inserted.
require(
sellOrders[auctionId].remove(orders[i]),
"order is no longer claimable"
);
}
AuctionData memory auction = auctionData[auctionId];
(, uint96 priceNumerator, uint96 priceDenominator) =
auction.clearingPriceOrder.decodeOrder();
(uint64 userId, , ) = orders[0].decodeOrder();
bool minFundingThresholdNotReached =
auctionData[auctionId].minFundingThresholdNotReached;
for (uint256 i = 0; i < orders.length; i++) {
(uint64 userIdOrder, uint96 buyAmount, uint96 sellAmount) =
orders[i].decodeOrder();
require(
userIdOrder == userId,
"only allowed to claim for same user"
);
if (minFundingThresholdNotReached) {
//[10]
sumBiddingTokenAmount = sumBiddingTokenAmount.add(sellAmount);
} else {
//[23]
if (orders[i] == auction.clearingPriceOrder) {
//[25]
sumAuctioningTokenAmount = sumAuctioningTokenAmount.add(
auction
.volumeClearingPriceOrder
.mul(priceNumerator)
.div(priceDenominator)
);
sumBiddingTokenAmount = sumBiddingTokenAmount.add(
sellAmount.sub(auction.volumeClearingPriceOrder)
);
} else {
if (orders[i].smallerThan(auction.clearingPriceOrder)) {
//[17]
sumAuctioningTokenAmount = sumAuctioningTokenAmount.add(
sellAmount.mul(priceNumerator).div(priceDenominator)
);
} else {
//[24]
sumBiddingTokenAmount = sumBiddingTokenAmount.add(
sellAmount
);
}
}
}
emit ClaimedFromOrder(auctionId, userId, buyAmount, sellAmount);
}
sendOutTokens(
auctionId,
sumAuctioningTokenAmount,
sumBiddingTokenAmount,
userId
); //[3]
}
function processFeesAndAuctioneerFunds(
uint256 auctionId,
uint256 fillVolumeOfAuctioneerOrder,
uint64 auctioneerId,
uint96 fullAuctionedAmount
) internal {
uint256 feeAmount =
fullAuctionedAmount.mul(auctionData[auctionId].feeNumerator).div(
FEE_DENOMINATOR
); //[20]
if (auctionData[auctionId].minFundingThresholdNotReached) {
sendOutTokens(
auctionId,
fullAuctionedAmount.add(feeAmount),
0,
auctioneerId
); //[4]
} else {
//[11]
(, uint96 priceNumerator, uint96 priceDenominator) =
auctionData[auctionId].clearingPriceOrder.decodeOrder();
uint256 unsettledAuctionTokens =
fullAuctionedAmount.sub(fillVolumeOfAuctioneerOrder);
uint256 auctioningTokenAmount =
unsettledAuctionTokens.add(
feeAmount.mul(unsettledAuctionTokens).div(
fullAuctionedAmount
)
);
uint256 biddingTokenAmount =
fillVolumeOfAuctioneerOrder.mul(priceDenominator).div(
priceNumerator
);
sendOutTokens(
auctionId,
auctioningTokenAmount,
biddingTokenAmount,
auctioneerId
); //[5]
sendOutTokens(
auctionId,
feeAmount.mul(fillVolumeOfAuctioneerOrder).div(
fullAuctionedAmount
),
0,
feeReceiverUserId
); //[7]
}
}
function sendOutTokens(
uint256 auctionId,
uint256 auctioningTokenAmount,
uint256 biddingTokenAmount,
uint64 userId
) internal {
address userAddress = registeredUsers.getAddressAt(userId);
if (auctioningTokenAmount > 0) {
auctionData[auctionId].auctioningToken.safeTransfer(
userAddress,
auctioningTokenAmount
);
}
if (biddingTokenAmount > 0) {
auctionData[auctionId].biddingToken.safeTransfer(
userAddress,
biddingTokenAmount
);
}
}
function registerUser(address user) public returns (uint64 userId) {
numUsers = numUsers.add(1).toUint64();
require(
registeredUsers.insert(numUsers, user),
"User already registered"
);
userId = numUsers;
emit UserRegistration(user, userId);
}
function getUserId(address user) public returns (uint64 userId) {
if (registeredUsers.hasAddress(user)) {
userId = registeredUsers.getId(user);
} else {
userId = registerUser(user);
emit NewUser(userId, user);
}
}
function getSecondsRemainingInBatch(uint256 auctionId)
public
view
returns (uint256)
{
if (auctionData[auctionId].auctionEndDate < block.timestamp) {
return 0;
}
return auctionData[auctionId].auctionEndDate.sub(block.timestamp);
}
function containsOrder(uint256 auctionId, bytes32 order)
public
view
returns (bool)
{
return sellOrders[auctionId].contains(order);
}
} | initiateAuction | function initiateAuction(
IERC20 _auctioningToken,
IERC20 _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
bool isAtomicClosureAllowed,
address accessManagerContract,
bytes memory accessManagerContractData
) public returns (uint256) {
// withdraws sellAmount + fees
_auctioningToken.safeTransferFrom(
msg.sender,
address(this),
_auctionedSellAmount.mul(FEE_DENOMINATOR.add(feeNumerator)).div(
FEE_DENOMINATOR
) //[0]
);
require(_auctionedSellAmount > 0, "cannot auction zero tokens");
require(_minBuyAmount > 0, "tokens cannot be auctioned for free");
require(
minimumBiddingAmountPerOrder > 0,
"minimumBiddingAmountPerOrder is not allowed to be zero"
);
require(
orderCancellationEndDate <= auctionEndDate,
"time periods are not configured correctly"
);
require(
auctionEndDate > block.timestamp,
"auction end date must be in the future"
);
auctionCounter = auctionCounter.add(1);
sellOrders[auctionCounter].initializeEmptyList();
uint64 userId = getUserId(msg.sender);
auctionData[auctionCounter] = AuctionData(
_auctioningToken,
_biddingToken,
orderCancellationEndDate,
auctionEndDate,
IterableOrderedOrderSet.encodeOrder(
userId,
_minBuyAmount,
_auctionedSellAmount
),
minimumBiddingAmountPerOrder,
0,
IterableOrderedOrderSet.QUEUE_START,
bytes32(0),
0,
false,
isAtomicClosureAllowed,
feeNumerator,
minFundingThreshold
);
auctionAccessManager[auctionCounter] = accessManagerContract;
auctionAccessData[auctionCounter] = accessManagerContractData;
emit NewAuction(
auctionCounter,
_auctioningToken,
_biddingToken,
orderCancellationEndDate,
auctionEndDate,
userId,
_auctionedSellAmount,
_minBuyAmount,
minimumBiddingAmountPerOrder,
minFundingThreshold,
accessManagerContract,
accessManagerContractData
);
return auctionCounter;
}
| // @dev: function to intiate a new auction
// Warning: In case the auction is expected to raise more than
// 2^96 units of the biddingToken, don't start the auction, as
// it will not be settlable. This corresponds to about 79
// billion DAI.
//
// Prices between biddingToken and auctioningToken are expressed by a
// fraction whose components are stored as uint96. | LineComment | v0.6.12+commit.27d51765 | None | {
"func_code_index": [
4641,
7290
]
} | 198 |
|||
EasyAuction | contracts/EasyAuction.sol | 0x0b7ffc1f4ad541a4ed16b40d8c37f0929158d101 | Solidity | EasyAuction | contract EasyAuction is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint64;
using SafeMath for uint96;
using SafeMath for uint256;
using SafeCast for uint256;
using IterableOrderedOrderSet for IterableOrderedOrderSet.Data;
using IterableOrderedOrderSet for bytes32;
using IdToAddressBiMap for IdToAddressBiMap.Data;
modifier atStageOrderPlacement(uint256 auctionId) {
require(
block.timestamp < auctionData[auctionId].auctionEndDate,
"no longer in order placement phase"
);
_;
}
modifier atStageOrderPlacementAndCancelation(uint256 auctionId) {
require(
block.timestamp < auctionData[auctionId].orderCancellationEndDate,
"no longer in order placement and cancelation phase"
);
_;
}
modifier atStageSolutionSubmission(uint256 auctionId) {
{
uint256 auctionEndDate = auctionData[auctionId].auctionEndDate;
require(
auctionEndDate != 0 &&
block.timestamp >= auctionEndDate &&
auctionData[auctionId].clearingPriceOrder == bytes32(0),
"Auction not in solution submission phase"
);
}
_;
}
modifier atStageFinished(uint256 auctionId) {
require(
auctionData[auctionId].clearingPriceOrder != bytes32(0),
"Auction not yet finished"
);
_;
}
event NewSellOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event CancellationSellOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event ClaimedFromOrder(
uint256 indexed auctionId,
uint64 indexed userId,
uint96 buyAmount,
uint96 sellAmount
);
event NewUser(uint64 indexed userId, address indexed userAddress);
event NewAuction(
uint256 indexed auctionId,
IERC20 indexed _auctioningToken,
IERC20 indexed _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint64 userId,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
address allowListContract,
bytes allowListData
);
event AuctionCleared(
uint256 indexed auctionId,
uint96 soldAuctioningTokens,
uint96 soldBiddingTokens,
bytes32 clearingPriceOrder
);
event UserRegistration(address indexed user, uint64 userId);
struct AuctionData {
IERC20 auctioningToken;
IERC20 biddingToken;
uint256 orderCancellationEndDate;
uint256 auctionEndDate;
bytes32 initialAuctionOrder;
uint256 minimumBiddingAmountPerOrder;
uint256 interimSumBidAmount;
bytes32 interimOrder;
bytes32 clearingPriceOrder;
uint96 volumeClearingPriceOrder;
bool minFundingThresholdNotReached;
bool isAtomicClosureAllowed;
uint256 feeNumerator;
uint256 minFundingThreshold;
}
mapping(uint256 => IterableOrderedOrderSet.Data) internal sellOrders;
mapping(uint256 => AuctionData) public auctionData;
mapping(uint256 => address) public auctionAccessManager;
mapping(uint256 => bytes) public auctionAccessData;
IdToAddressBiMap.Data private registeredUsers;
uint64 public numUsers;
uint256 public auctionCounter;
constructor() public Ownable() {}
uint256 public feeNumerator = 0;
uint256 public constant FEE_DENOMINATOR = 1000;
uint64 public feeReceiverUserId = 1;
function setFeeParameters(
uint256 newFeeNumerator,
address newfeeReceiverAddress
) public onlyOwner() {
require(
newFeeNumerator <= 15,
"Fee is not allowed to be set higher than 1.5%"
);
// caution: for currently running auctions, the feeReceiverUserId is changing as well.
feeReceiverUserId = getUserId(newfeeReceiverAddress);
feeNumerator = newFeeNumerator;
}
// @dev: function to intiate a new auction
// Warning: In case the auction is expected to raise more than
// 2^96 units of the biddingToken, don't start the auction, as
// it will not be settlable. This corresponds to about 79
// billion DAI.
//
// Prices between biddingToken and auctioningToken are expressed by a
// fraction whose components are stored as uint96.
function initiateAuction(
IERC20 _auctioningToken,
IERC20 _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
bool isAtomicClosureAllowed,
address accessManagerContract,
bytes memory accessManagerContractData
) public returns (uint256) {
// withdraws sellAmount + fees
_auctioningToken.safeTransferFrom(
msg.sender,
address(this),
_auctionedSellAmount.mul(FEE_DENOMINATOR.add(feeNumerator)).div(
FEE_DENOMINATOR
) //[0]
);
require(_auctionedSellAmount > 0, "cannot auction zero tokens");
require(_minBuyAmount > 0, "tokens cannot be auctioned for free");
require(
minimumBiddingAmountPerOrder > 0,
"minimumBiddingAmountPerOrder is not allowed to be zero"
);
require(
orderCancellationEndDate <= auctionEndDate,
"time periods are not configured correctly"
);
require(
auctionEndDate > block.timestamp,
"auction end date must be in the future"
);
auctionCounter = auctionCounter.add(1);
sellOrders[auctionCounter].initializeEmptyList();
uint64 userId = getUserId(msg.sender);
auctionData[auctionCounter] = AuctionData(
_auctioningToken,
_biddingToken,
orderCancellationEndDate,
auctionEndDate,
IterableOrderedOrderSet.encodeOrder(
userId,
_minBuyAmount,
_auctionedSellAmount
),
minimumBiddingAmountPerOrder,
0,
IterableOrderedOrderSet.QUEUE_START,
bytes32(0),
0,
false,
isAtomicClosureAllowed,
feeNumerator,
minFundingThreshold
);
auctionAccessManager[auctionCounter] = accessManagerContract;
auctionAccessData[auctionCounter] = accessManagerContractData;
emit NewAuction(
auctionCounter,
_auctioningToken,
_biddingToken,
orderCancellationEndDate,
auctionEndDate,
userId,
_auctionedSellAmount,
_minBuyAmount,
minimumBiddingAmountPerOrder,
minFundingThreshold,
accessManagerContract,
accessManagerContractData
);
return auctionCounter;
}
function placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData
) external atStageOrderPlacement(auctionId) returns (uint64 userId) {
return
_placeSellOrders(
auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
allowListCallData,
msg.sender
);
}
function placeSellOrdersOnBehalf(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData,
address orderSubmitter
) external atStageOrderPlacement(auctionId) returns (uint64 userId) {
return
_placeSellOrders(
auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
allowListCallData,
orderSubmitter
);
}
function _placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData,
address orderSubmitter
) internal returns (uint64 userId) {
{
address allowListManger = auctionAccessManager[auctionId];
if (allowListManger != address(0)) {
require(
AllowListVerifier(allowListManger).isAllowed(
orderSubmitter,
auctionId,
allowListCallData
) == AllowListVerifierHelper.MAGICVALUE,
"user not allowed to place order"
);
}
}
{
(
,
uint96 buyAmountOfInitialAuctionOrder,
uint96 sellAmountOfInitialAuctionOrder
) = auctionData[auctionId].initialAuctionOrder.decodeOrder();
for (uint256 i = 0; i < _minBuyAmounts.length; i++) {
require(
_minBuyAmounts[i].mul(buyAmountOfInitialAuctionOrder) <
sellAmountOfInitialAuctionOrder.mul(_sellAmounts[i]),
"limit price not better than mimimal offer"
);
}
}
uint256 sumOfSellAmounts = 0;
userId = getUserId(orderSubmitter);
uint256 minimumBiddingAmountPerOrder =
auctionData[auctionId].minimumBiddingAmountPerOrder;
for (uint256 i = 0; i < _minBuyAmounts.length; i++) {
require(
_minBuyAmounts[i] > 0,
"_minBuyAmounts must be greater than 0"
);
// orders should have a minimum bid size in order to limit the gas
// required to compute the final price of the auction.
require(
_sellAmounts[i] > minimumBiddingAmountPerOrder,
"order too small"
);
if (
sellOrders[auctionId].insert(
IterableOrderedOrderSet.encodeOrder(
userId,
_minBuyAmounts[i],
_sellAmounts[i]
),
_prevSellOrders[i]
)
) {
sumOfSellAmounts = sumOfSellAmounts.add(_sellAmounts[i]);
emit NewSellOrder(
auctionId,
userId,
_minBuyAmounts[i],
_sellAmounts[i]
);
}
}
auctionData[auctionId].biddingToken.safeTransferFrom(
msg.sender,
address(this),
sumOfSellAmounts
); //[1]
}
function cancelSellOrders(uint256 auctionId, bytes32[] memory _sellOrders)
public
atStageOrderPlacementAndCancelation(auctionId)
{
uint64 userId = getUserId(msg.sender);
uint256 claimableAmount = 0;
for (uint256 i = 0; i < _sellOrders.length; i++) {
// Note: we keep the back pointer of the deleted element so that
// it can be used as a reference point to insert a new node.
bool success =
sellOrders[auctionId].removeKeepHistory(_sellOrders[i]);
if (success) {
(
uint64 userIdOfIter,
uint96 buyAmountOfIter,
uint96 sellAmountOfIter
) = _sellOrders[i].decodeOrder();
require(
userIdOfIter == userId,
"Only the user can cancel his orders"
);
claimableAmount = claimableAmount.add(sellAmountOfIter);
emit CancellationSellOrder(
auctionId,
userId,
buyAmountOfIter,
sellAmountOfIter
);
}
}
auctionData[auctionId].biddingToken.safeTransfer(
msg.sender,
claimableAmount
); //[2]
}
function precalculateSellAmountSum(
uint256 auctionId,
uint256 iterationSteps
) public atStageSolutionSubmission(auctionId) {
(, , uint96 auctioneerSellAmount) =
auctionData[auctionId].initialAuctionOrder.decodeOrder();
uint256 sumBidAmount = auctionData[auctionId].interimSumBidAmount;
bytes32 iterOrder = auctionData[auctionId].interimOrder;
for (uint256 i = 0; i < iterationSteps; i++) {
iterOrder = sellOrders[auctionId].next(iterOrder);
(, , uint96 sellAmountOfIter) = iterOrder.decodeOrder();
sumBidAmount = sumBidAmount.add(sellAmountOfIter);
}
require(
iterOrder != IterableOrderedOrderSet.QUEUE_END,
"reached end of order list"
);
// it is checked that not too many iteration steps were taken:
// require that the sum of SellAmounts times the price of the last order
// is not more than initially sold amount
(, uint96 buyAmountOfIter, uint96 sellAmountOfIter) =
iterOrder.decodeOrder();
require(
sumBidAmount.mul(buyAmountOfIter) <
auctioneerSellAmount.mul(sellAmountOfIter),
"too many orders summed up"
);
auctionData[auctionId].interimSumBidAmount = sumBidAmount;
auctionData[auctionId].interimOrder = iterOrder;
}
function settleAuctionAtomically(
uint256 auctionId,
uint96[] memory _minBuyAmount,
uint96[] memory _sellAmount,
bytes32[] memory _prevSellOrder,
bytes calldata allowListCallData
) public atStageSolutionSubmission(auctionId) {
require(
auctionData[auctionId].isAtomicClosureAllowed,
"not allowed to settle auction atomically"
);
require(
_minBuyAmount.length == 1 && _sellAmount.length == 1,
"Only one order can be placed atomically"
);
uint64 userId = getUserId(msg.sender);
require(
auctionData[auctionId].interimOrder.smallerThan(
IterableOrderedOrderSet.encodeOrder(
userId,
_minBuyAmount[0],
_sellAmount[0]
)
),
"precalculateSellAmountSum is already too advanced"
);
_placeSellOrders(
auctionId,
_minBuyAmount,
_sellAmount,
_prevSellOrder,
allowListCallData,
msg.sender
);
settleAuction(auctionId);
}
// @dev function settling the auction and calculating the price
function settleAuction(uint256 auctionId)
public
atStageSolutionSubmission(auctionId)
returns (bytes32 clearingOrder)
{
(
uint64 auctioneerId,
uint96 minAuctionedBuyAmount,
uint96 fullAuctionedAmount
) = auctionData[auctionId].initialAuctionOrder.decodeOrder();
uint256 currentBidSum = auctionData[auctionId].interimSumBidAmount;
bytes32 currentOrder = auctionData[auctionId].interimOrder;
uint256 buyAmountOfIter;
uint256 sellAmountOfIter;
uint96 fillVolumeOfAuctioneerOrder = fullAuctionedAmount;
// Sum order up, until fullAuctionedAmount is fully bought or queue end is reached
do {
bytes32 nextOrder = sellOrders[auctionId].next(currentOrder);
if (nextOrder == IterableOrderedOrderSet.QUEUE_END) {
break;
}
currentOrder = nextOrder;
(, buyAmountOfIter, sellAmountOfIter) = currentOrder.decodeOrder();
currentBidSum = currentBidSum.add(sellAmountOfIter);
} while (
currentBidSum.mul(buyAmountOfIter) <
fullAuctionedAmount.mul(sellAmountOfIter)
);
if (
currentBidSum > 0 &&
currentBidSum.mul(buyAmountOfIter) >=
fullAuctionedAmount.mul(sellAmountOfIter)
) {
// All considered/summed orders are sufficient to close the auction fully
// at price between current and previous orders.
uint256 uncoveredBids =
currentBidSum.sub(
fullAuctionedAmount.mul(sellAmountOfIter).div(
buyAmountOfIter
)
);
if (sellAmountOfIter >= uncoveredBids) {
//[13]
// Auction fully filled via partial match of currentOrder
uint256 sellAmountClearingOrder =
sellAmountOfIter.sub(uncoveredBids);
auctionData[auctionId]
.volumeClearingPriceOrder = sellAmountClearingOrder
.toUint96();
currentBidSum = currentBidSum.sub(uncoveredBids);
clearingOrder = currentOrder;
} else {
//[14]
// Auction fully filled via price strictly between currentOrder and the order
// immediately before. For a proof, see the security-considerations.md
currentBidSum = currentBidSum.sub(sellAmountOfIter);
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
currentBidSum.toUint96()
);
}
} else {
// All considered/summed orders are not sufficient to close the auction fully at price of last order //[18]
// Either a higher price must be used or auction is only partially filled
if (currentBidSum > minAuctionedBuyAmount) {
//[15]
// Price higher than last order would fill the auction
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
currentBidSum.toUint96()
);
} else {
//[16]
// Even at the initial auction price, the auction is partially filled
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
minAuctionedBuyAmount
);
fillVolumeOfAuctioneerOrder = currentBidSum
.mul(fullAuctionedAmount)
.div(minAuctionedBuyAmount)
.toUint96();
}
}
auctionData[auctionId].clearingPriceOrder = clearingOrder;
if (auctionData[auctionId].minFundingThreshold > currentBidSum) {
auctionData[auctionId].minFundingThresholdNotReached = true;
}
processFeesAndAuctioneerFunds(
auctionId,
fillVolumeOfAuctioneerOrder,
auctioneerId,
fullAuctionedAmount
);
emit AuctionCleared(
auctionId,
fillVolumeOfAuctioneerOrder,
uint96(currentBidSum),
clearingOrder
);
// Gas refunds
auctionAccessManager[auctionId] = address(0);
delete auctionAccessData[auctionId];
auctionData[auctionId].initialAuctionOrder = bytes32(0);
auctionData[auctionId].interimOrder = bytes32(0);
auctionData[auctionId].interimSumBidAmount = uint256(0);
auctionData[auctionId].minimumBiddingAmountPerOrder = uint256(0);
}
function claimFromParticipantOrder(
uint256 auctionId,
bytes32[] memory orders
)
public
atStageFinished(auctionId)
returns (
uint256 sumAuctioningTokenAmount,
uint256 sumBiddingTokenAmount
)
{
for (uint256 i = 0; i < orders.length; i++) {
// Note: we don't need to keep any information about the node since
// no new elements need to be inserted.
require(
sellOrders[auctionId].remove(orders[i]),
"order is no longer claimable"
);
}
AuctionData memory auction = auctionData[auctionId];
(, uint96 priceNumerator, uint96 priceDenominator) =
auction.clearingPriceOrder.decodeOrder();
(uint64 userId, , ) = orders[0].decodeOrder();
bool minFundingThresholdNotReached =
auctionData[auctionId].minFundingThresholdNotReached;
for (uint256 i = 0; i < orders.length; i++) {
(uint64 userIdOrder, uint96 buyAmount, uint96 sellAmount) =
orders[i].decodeOrder();
require(
userIdOrder == userId,
"only allowed to claim for same user"
);
if (minFundingThresholdNotReached) {
//[10]
sumBiddingTokenAmount = sumBiddingTokenAmount.add(sellAmount);
} else {
//[23]
if (orders[i] == auction.clearingPriceOrder) {
//[25]
sumAuctioningTokenAmount = sumAuctioningTokenAmount.add(
auction
.volumeClearingPriceOrder
.mul(priceNumerator)
.div(priceDenominator)
);
sumBiddingTokenAmount = sumBiddingTokenAmount.add(
sellAmount.sub(auction.volumeClearingPriceOrder)
);
} else {
if (orders[i].smallerThan(auction.clearingPriceOrder)) {
//[17]
sumAuctioningTokenAmount = sumAuctioningTokenAmount.add(
sellAmount.mul(priceNumerator).div(priceDenominator)
);
} else {
//[24]
sumBiddingTokenAmount = sumBiddingTokenAmount.add(
sellAmount
);
}
}
}
emit ClaimedFromOrder(auctionId, userId, buyAmount, sellAmount);
}
sendOutTokens(
auctionId,
sumAuctioningTokenAmount,
sumBiddingTokenAmount,
userId
); //[3]
}
function processFeesAndAuctioneerFunds(
uint256 auctionId,
uint256 fillVolumeOfAuctioneerOrder,
uint64 auctioneerId,
uint96 fullAuctionedAmount
) internal {
uint256 feeAmount =
fullAuctionedAmount.mul(auctionData[auctionId].feeNumerator).div(
FEE_DENOMINATOR
); //[20]
if (auctionData[auctionId].minFundingThresholdNotReached) {
sendOutTokens(
auctionId,
fullAuctionedAmount.add(feeAmount),
0,
auctioneerId
); //[4]
} else {
//[11]
(, uint96 priceNumerator, uint96 priceDenominator) =
auctionData[auctionId].clearingPriceOrder.decodeOrder();
uint256 unsettledAuctionTokens =
fullAuctionedAmount.sub(fillVolumeOfAuctioneerOrder);
uint256 auctioningTokenAmount =
unsettledAuctionTokens.add(
feeAmount.mul(unsettledAuctionTokens).div(
fullAuctionedAmount
)
);
uint256 biddingTokenAmount =
fillVolumeOfAuctioneerOrder.mul(priceDenominator).div(
priceNumerator
);
sendOutTokens(
auctionId,
auctioningTokenAmount,
biddingTokenAmount,
auctioneerId
); //[5]
sendOutTokens(
auctionId,
feeAmount.mul(fillVolumeOfAuctioneerOrder).div(
fullAuctionedAmount
),
0,
feeReceiverUserId
); //[7]
}
}
function sendOutTokens(
uint256 auctionId,
uint256 auctioningTokenAmount,
uint256 biddingTokenAmount,
uint64 userId
) internal {
address userAddress = registeredUsers.getAddressAt(userId);
if (auctioningTokenAmount > 0) {
auctionData[auctionId].auctioningToken.safeTransfer(
userAddress,
auctioningTokenAmount
);
}
if (biddingTokenAmount > 0) {
auctionData[auctionId].biddingToken.safeTransfer(
userAddress,
biddingTokenAmount
);
}
}
function registerUser(address user) public returns (uint64 userId) {
numUsers = numUsers.add(1).toUint64();
require(
registeredUsers.insert(numUsers, user),
"User already registered"
);
userId = numUsers;
emit UserRegistration(user, userId);
}
function getUserId(address user) public returns (uint64 userId) {
if (registeredUsers.hasAddress(user)) {
userId = registeredUsers.getId(user);
} else {
userId = registerUser(user);
emit NewUser(userId, user);
}
}
function getSecondsRemainingInBatch(uint256 auctionId)
public
view
returns (uint256)
{
if (auctionData[auctionId].auctionEndDate < block.timestamp) {
return 0;
}
return auctionData[auctionId].auctionEndDate.sub(block.timestamp);
}
function containsOrder(uint256 auctionId, bytes32 order)
public
view
returns (bool)
{
return sellOrders[auctionId].contains(order);
}
} | settleAuction | function settleAuction(uint256 auctionId)
public
atStageSolutionSubmission(auctionId)
returns (bytes32 clearingOrder)
{
(
uint64 auctioneerId,
uint96 minAuctionedBuyAmount,
uint96 fullAuctionedAmount
) = auctionData[auctionId].initialAuctionOrder.decodeOrder();
uint256 currentBidSum = auctionData[auctionId].interimSumBidAmount;
bytes32 currentOrder = auctionData[auctionId].interimOrder;
uint256 buyAmountOfIter;
uint256 sellAmountOfIter;
uint96 fillVolumeOfAuctioneerOrder = fullAuctionedAmount;
// Sum order up, until fullAuctionedAmount is fully bought or queue end is reached
do {
bytes32 nextOrder = sellOrders[auctionId].next(currentOrder);
if (nextOrder == IterableOrderedOrderSet.QUEUE_END) {
break;
}
currentOrder = nextOrder;
(, buyAmountOfIter, sellAmountOfIter) = currentOrder.decodeOrder();
currentBidSum = currentBidSum.add(sellAmountOfIter);
} while (
currentBidSum.mul(buyAmountOfIter) <
fullAuctionedAmount.mul(sellAmountOfIter)
);
if (
currentBidSum > 0 &&
currentBidSum.mul(buyAmountOfIter) >=
fullAuctionedAmount.mul(sellAmountOfIter)
) {
// All considered/summed orders are sufficient to close the auction fully
// at price between current and previous orders.
uint256 uncoveredBids =
currentBidSum.sub(
fullAuctionedAmount.mul(sellAmountOfIter).div(
buyAmountOfIter
)
);
if (sellAmountOfIter >= uncoveredBids) {
//[13]
// Auction fully filled via partial match of currentOrder
uint256 sellAmountClearingOrder =
sellAmountOfIter.sub(uncoveredBids);
auctionData[auctionId]
.volumeClearingPriceOrder = sellAmountClearingOrder
.toUint96();
currentBidSum = currentBidSum.sub(uncoveredBids);
clearingOrder = currentOrder;
} else {
//[14]
// Auction fully filled via price strictly between currentOrder and the order
// immediately before. For a proof, see the security-considerations.md
currentBidSum = currentBidSum.sub(sellAmountOfIter);
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
currentBidSum.toUint96()
);
}
} else {
// All considered/summed orders are not sufficient to close the auction fully at price of last order //[18]
// Either a higher price must be used or auction is only partially filled
if (currentBidSum > minAuctionedBuyAmount) {
//[15]
// Price higher than last order would fill the auction
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
currentBidSum.toUint96()
);
} else {
//[16]
// Even at the initial auction price, the auction is partially filled
clearingOrder = IterableOrderedOrderSet.encodeOrder(
0,
fullAuctionedAmount,
minAuctionedBuyAmount
);
fillVolumeOfAuctioneerOrder = currentBidSum
.mul(fullAuctionedAmount)
.div(minAuctionedBuyAmount)
.toUint96();
}
}
auctionData[auctionId].clearingPriceOrder = clearingOrder;
if (auctionData[auctionId].minFundingThreshold > currentBidSum) {
auctionData[auctionId].minFundingThresholdNotReached = true;
}
processFeesAndAuctioneerFunds(
auctionId,
fillVolumeOfAuctioneerOrder,
auctioneerId,
fullAuctionedAmount
);
emit AuctionCleared(
auctionId,
fillVolumeOfAuctioneerOrder,
uint96(currentBidSum),
clearingOrder
);
// Gas refunds
auctionAccessManager[auctionId] = address(0);
delete auctionAccessData[auctionId];
auctionData[auctionId].initialAuctionOrder = bytes32(0);
auctionData[auctionId].interimOrder = bytes32(0);
auctionData[auctionId].interimSumBidAmount = uint256(0);
auctionData[auctionId].minimumBiddingAmountPerOrder = uint256(0);
}
| // @dev function settling the auction and calculating the price | LineComment | v0.6.12+commit.27d51765 | None | {
"func_code_index": [
15242,
20072
]
} | 199 |
|||
HogeNFTv3 | HogeNFTv3.sol | 0xae58a033b6d7e66014fe88227c97680cc6ccecd9 | Solidity | EnumerableMap | library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
} | _set | function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
| /**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://c9934b71fc610797d2cdb07781f8b745bc463b58cb1b7325cc49abe91d425949 | {
"func_code_index": [
1091,
1788
]
} | 200 |
||
HogeNFTv3 | HogeNFTv3.sol | 0xae58a033b6d7e66014fe88227c97680cc6ccecd9 | Solidity | EnumerableMap | library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
} | _remove | function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
| /**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://c9934b71fc610797d2cdb07781f8b745bc463b58cb1b7325cc49abe91d425949 | {
"func_code_index": [
1958,
3512
]
} | 201 |
||
HogeNFTv3 | HogeNFTv3.sol | 0xae58a033b6d7e66014fe88227c97680cc6ccecd9 | Solidity | EnumerableMap | library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
} | _contains | function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
| /**
* @dev Returns true if the key is in the map. O(1).
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://c9934b71fc610797d2cdb07781f8b745bc463b58cb1b7325cc49abe91d425949 | {
"func_code_index": [
3591,
3721
]
} | 202 |
||
HogeNFTv3 | HogeNFTv3.sol | 0xae58a033b6d7e66014fe88227c97680cc6ccecd9 | Solidity | EnumerableMap | library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
} | _length | function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
| /**
* @dev Returns the number of key-value pairs in the map. O(1).
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://c9934b71fc610797d2cdb07781f8b745bc463b58cb1b7325cc49abe91d425949 | {
"func_code_index": [
3811,
3926
]
} | 203 |
||
HogeNFTv3 | HogeNFTv3.sol | 0xae58a033b6d7e66014fe88227c97680cc6ccecd9 | Solidity | EnumerableMap | library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
} | _at | function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
| /**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://c9934b71fc610797d2cdb07781f8b745bc463b58cb1b7325cc49abe91d425949 | {
"func_code_index": [
4286,
4570
]
} | 204 |
||
HogeNFTv3 | HogeNFTv3.sol | 0xae58a033b6d7e66014fe88227c97680cc6ccecd9 | Solidity | EnumerableMap | library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
} | _tryGet | function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
| /**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://c9934b71fc610797d2cdb07781f8b745bc463b58cb1b7325cc49abe91d425949 | {
"func_code_index": [
4713,
5026
]
} | 205 |
||
HogeNFTv3 | HogeNFTv3.sol | 0xae58a033b6d7e66014fe88227c97680cc6ccecd9 | Solidity | EnumerableMap | library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
} | _get | function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
| /**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | MIT | ipfs://c9934b71fc610797d2cdb07781f8b745bc463b58cb1b7325cc49abe91d425949 | {
"func_code_index": [
5182,
5498
]
} | 206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.